【问题标题】:iframe.document.body.scrollHeight is double the correct valueiframe.document.body.scrollHeight 是正确值的两倍
【发布时间】:2011-02-10 16:45:42
【问题描述】:

<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';

            }
        }

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

这是 Firefox 中的正确高度。

在我只通过将 IE 值 /2 来修补之前,这样做的正确方法是什么?

【问题讨论】:

    标签: javascript iframe cross-browser


    【解决方案1】:

    document.body 代表 IE 在 Quirks 模式下运行时的视口。如果 iframe 中的文档在 Quirks 中,则 bodyscrollHeight 将等于其视口的高度,即。 iframe 的默认高度。

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

    另外,你不应该使用document.all 进行 IE 嗅探(这对于支持它的其他浏览器可能会出错),你不应该使用 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';
    }
    

    【讨论】:

    • 在 IE7 中,这只是给我窗口的预先存在的高度,而不是其内容的大小。帮助? :-)
    • 正如我所说,这就是 Quirks 模式中会发生的事情。在标准模式下,body 实际上是 <body> 元素中内容的高度。不要使用怪癖模式。不好看。
    • 我无法完全控制 iframe 中的内容,它是另一个组中的某个人,我必须让他们帮助我。除此之外,谢谢!
    • 如果到目前为止有人关注过这个,下面的链接有助于清除哪些 DOCTYPE 标头会触发怪癖模式,哪些不会:hsivonen.iki.fi/doctype
    • @Nelson:它是什么:在 IE 的每个元素节点上都有一个属性 document。它是 Node 上标准 DOM ownerDocument 属性的未记录同义词。所以iframe.document===document——父文档,而不是子 iframe 文档。所以你会得到父窗口的高度而不是子 iframe(假设你实际上做了iframe.document.documentElement.scrollHeight;没有document.scrollHeight 属性)。
    【解决方案2】:

    尝试使用这个

    function change_height(iframe) {
        var doc= 'contentDocument' in iframe? iframe.contentDocument : iframe.contentWindow.document;
        iframe.style.height= doc.body.scrollHeight+'px';
    }
    

    我还修改了 jquery 使用的代码

    (function($) {
        $.fn.ZIAutoHeight = function() {
            var t = this, doc = 'contentDocument' in t[0]? t[0].contentDocument : t[0].contentWindow.document;
            t.css('height', doc.body.scrollHeight+'px');
        }
    })(jQuery);
    

    使用$('iframe').ZIAutoHeight();希望对你有帮助

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-05
      • 1970-01-01
      • 2010-12-07
      • 2018-09-17
      • 2019-06-16
      相关资源
      最近更新 更多