在 Firefox 中,父容器包含浮動子元素且未清除浮動時,offsetHeight 回傳 0(IE 正常)。若在除錯器中檢視物件屬性卻能看到正確值,因為除錯器會觸發重新計算。
<div id="outer"></div>
<script>
window.onload = function() {
var html = '<div id="divcj" style="margin-top:15px;font-size:10px;width:400px;">'
+ '<div style="float:left;width:50px;">測試</div>'
+ '<div style="float:left;width:320px;">danielinbiti</div>'
+ '</div>'
+ '<div id="divcj2" style="margin-top:15px;font-size:10px;width:400px;">'
+ '<div style="width:320px;">danielinbiti</div>'
+ '</div>';
document.getElementById('outer').innerHTML = html;
document.getElementById('divcj2').style.display = 'none';
alert(document.getElementById('divcj2').offsetHeight); // 正常
alert(document.getElementById('divcj').offsetHeight); // Firefox 為 0
};
</script>
浮動元素脫離文件流,父容器未建立 BFC(Block Formatting Context),導致高度為 0。Firefox 嚴格遵循標準,IE 則自動包含浮動(hasLayout 機制)。
.clearfix::after { content:""; display:block; clear:both; }
.clearfix { *zoom:1; }
<div id="divcj" ...>...浮動內容...</div>
<div id="divcj2" style="display:none;">...相同內容但移除 float...</div>
// 取 divcj2.offsetHeight 作為 divcj 高度
適用於極簡場景,但維護成本高(雙份 DOM)。.clearfix 於所有包含浮動子元素的容器。offsetHeight 前,可先強制觸發重排:element.getBoundingClientRect() 或讀取 offsetParent。