javascript 检测 iframe 内容高度变化

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4513266/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 13:57:58  来源:igfitidea点击:

Detect iframe content height change

javascriptiframe

提问by Nelson Rothermel

There are plentyof examples showing how to dynamically set an iframe's height to its content. This works perfect for me. The problem I'm now having is that the content can change size without triggering onload(think hidden/expandable divs).

很多示例展示了如何动态设置iframe的高度与其内容。这对我来说很完美。我现在遇到的问题是内容可以在不触发的情况下改变大小onload(想想 hidden/expandable divs)。

Is there any way to detect when the size of the iframecontent has changed? This is on the same domain and no jQuery, please.

有什么方法可以检测iframe内容的大小何时发生变化?这是在同一个域上,请不要使用 jQuery。

回答by lonesomeday

I would do this by polling regularly (maybe every 200 milliseconds, perhaps more often) using setInterval. You could then compare the size of the content to what it was last time.

我会通过使用setInterval. 然后,您可以将内容的大小与上次的大小进行比较。

var iframe = document.getElementById('myIframe'),
    lastheight;

setInterval(function(){
    if (iframe.document.body.scrollheight != lastheight) {
        // adjust the iframe's size

        lastheight = iframe.document.body.scrollheight;
    }
}, 200);

回答by kstrieder

For non-webkit browsers, there are a few domMutation-Events, that fire when an attribute of an element (e.g. the body element) change. See DOMSubtreeModified and more importantly DOMAttrModified.

对于非 webkit 浏览器,有一些 domMutation-Events,当元素的属性(例如 body 元素)更改时会触发。请参阅 DOMSubtreeModified,更重要的是 DOMAttrModified。

The internet explorer does fire the onresize event even on non-windows elements.

即使在非 Windows 元素上,Internet Explorer 也会触发 onresize 事件。

Opera honors the domMutation Events.

Opera 尊重 domMutation 事件。

Webkit on the other discarded these events as a compromise to rendering speed and javascript-performance. Thee is no other way than to check via timeout/interval the effective size of an element.

另一方面,Webkit 放弃了这些事件,作为对渲染速度和 javascript 性能的妥协。除了通过超时/间隔检查元素的有效大小之外,别无他法。