iframe.document.body.scrollHeight是正确值的两倍

Dea*_*n J 3 javascript iframe cross-browser

<iframe name="asdf" id="asdf" onload="change_height(this)" src="asdf.jsp" width="250" scrolling="no" frameborder="0"></iframe>

        function change_height(iframe) {
            if (document.all) {
                // IE.
                ieheight = iframe.document.body.scrollHeight;
                iframe.style.height = ieheight;
            } else {
                // Firefox.
                ffheight= iframe.contentDocument.body.offsetHeight;
                iframe.style.height = ffheight+ 'px';

            }
        }
Run Code Online (Sandbox Code Playgroud)

在IE7中运行时,ieheight是实际高度的两倍; 尚未在IE6上测试过.如果我使用scrollHeightoffsetHeight,它的值是相同的.

它是Firefox中正确的高度.

在我通过划分IE值/ 2来修补此问题之前,有什么方法可以做到这一点?

bob*_*nce 8

document.bodyIE在Quirks模式下运行时表示视口.如果iframe中的文档位于Quirks中,则scrollHeightbody将等于其视口的高度,即.iframe的默认高度.

如果你真的需要在Quirks模式下获得文档高度,你必须添加一个额外的包装div来测量.更好的解决方法是确保所有文档都使用标准模式doctype.在这十年中,你不应该用Quirks Mode创作任何东西.

此外,你不应该使用document.allIE嗅探(这可能是其他支持它的浏览器出错),你不应该使用iframe.document(它是非标准的,甚至没有MSDN记录),你应该总是添加'px'单位(IE可以应对它很好,你需要它在标准模式).

function change_height(iframe) {
    var doc= 'contentDocument' in iframe? iframe.contentDocument : iframe.contentWindow.document;
    iframe.style.height= doc.body.offsetHeight+'px';
}
Run Code Online (Sandbox Code Playgroud)