我正在调整几个 DIV 的高度contenteditable = true
修复 IE Quirksmode 下的盒子模型问题。
DIV 的样式为:
height: 14px;
padding: 6px;
border: 1px solid black;
overflow: hidden;
到目前为止,我一直在使用以下方法获取 CSS 高度值$("selector").css("height")
并使用该值进行进一步计算,但最近将我的 jQuery 库更新到最新版本,并且此方法现在已损坏。
详细说明;在 jQuery 1.4.2 中.css("height")
如果元素及其所有祖先都可见,则将返回“14px”,而 jQuery 1.6.2 将返回“0px”,否则返回“14px”。
我猜测前者是使用 IE Quirksmode 盒模型(14px 高度 - 2x 6px 填充 - 2x 1px 边框 = 0px)计算的,后者是直接从样式表中获取的。我想获得前者,无论可见性如何 - 有没有任何“漂亮”的方式来获取实际的 CSS 值(“漂亮”意味着不在 document.styleSheets 数组中查找它)?
Edit:
首先,我忘记了 DIV 上的一个重要的样式属性:overflow: hidden
(现已更正)。
另外我认为值得强调的是,此问题仅发生在 Internet Explorer 处于 Quirks 模式下时。据我所知,这在任何其他(当前)浏览器/模式中都不是问题(我没有测试全部,所以不能 100% 确定)。
为了进一步详细说明问题(并回答一些有关可能解决方案的建议),我对 jQuery 中的字段和不同函数返回的值进行了一些测试:
jQuery 1.4.2:
Element visible: true
.css('height'): 14px
.height(): 0
.outerHeight(): 14
Element visible: false
.css('height'): 14px
.height(): 0
.outerHeight(): 0
jQuery 1.6.2:
Element visible: true
.css('height'): 0
.height(): 0
.outerHeight(): 14
Element visible: false
.css('height'): 14px
.height(): 14
.outerHeight(): 28
.outerHeight(true)
对我来说没有用,因为无论盒子模型如何,边距都没有影响。元素可见性测试使用$("selector").is(":visible")
.
对了,那么如何使用这些数字呢?要固定盒模型高度,我必须进行以下计算:
newHeight = oldHeight + borderWidth (top & bottom) + padding (top & bottom)
换句话说,我需要 14px 值。有人可能会说,解决问题的办法就是抓住.outerHeight()
当元素可见并获取值时.css('height')
当它不是时(这就是我目前计划做的),但这实际上并没有回答原来的问题;如何获取实际的 CSS 值?
为了完整起见,这里有一个示例 HTML/脚本,它将复制我在测试中的数字(我没有对此进行实际测试,但最终结果是相同的 - 还记得在测试之前将 IE 设置为 Quirksmode) :
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="http://code.jquery.com/jquery-1.6.2.js" type="text/javascript"></script>
<style>
.input {
height: 14px;
padding: 6px 8px;
border: 1px solid black;
overflow: hidden;
}
.hidden { display: none; }
</style>
</head>
<body>
<div><div class="input" contenteditable="true">test</div></div>
<div class="hidden"><div class="input" contenteditable="true">test</div></div>
<script type="text/javascript">
$(document).ready(function(){
var t = "";
$(".input").each(function(){
t+= "visible: " + $(this).is(":visible") +"\n" +
".css('height'): " + $(this).css("height")+ "\n" +
".height(): " + $(this).height()+ "\n" +
".outerHeight(): " + $(this).outerHeight()+ "\n\n";
});
alert(t);
});
</script>
</body>
</html>