在内容刷新或更新时调整iframe的大小

我有一个iframe,每当内容自动刷新(每隔几分钟)或用户与之交互时,我想resize以匹配其内容。 虽然内容属于同一个域,但我很难修改内容。 理想情况下,iframe只会自行调整其内容的大小。

仅调整一次的当前代码:

 blah not supported blah   function setIframeHeight(iframe) { if (iframe) { var iframeWin = iframe.contentWindow || iframe.contentDocument.parentWindow; if (iframeWin.document.body) { iframe.height = iframeWin.document.documentElement.scrollHeight || iframeWin.document.body.scrollHeight; } } } $(window).load(function () { setIframeHeight(document.getElementById('ganglia-frame')); });  

相关问题: 调整iframe的宽度高度以适应其中的内容

您需要做的是设置一个计时器并在片刻之后检查iFrame大小。 您可能需要多次检查,因为并非所有浏览器都会立即返回正确的大小。

此方法仅适用于同域iFrame。

将函数绑定到iFrame onload事件,并在执行时检查iFrame的高度。 如果没有找到高度,请在几分钟后安排另一次检查。

 var iFrameSizeCount = 0; var onloadFunction = function(event){ var contentHeight = document.getElementById('iFrameId').contentWindow.document.body.offsetHeight; if(contentHeight == 0){ // Schedule a recheck in a few moments iFrameSizeCount++; // we keep a count of how many times we loop just in case if(iFrameSizeCount < 10){ // after a while we have to stop checking and call it a fail setTimeout(function(){ onloadFunction(event); }, 200); return false; } else { contentHeight = 100; // eventually if the check fails, default to a fixed height. You could possibly turn scrolling to auto/yes here to give the iFrame scrollbars. } } contentHeight += 30; // add some extra padding (some browsers give a height that's slightly too short) document.getElementById('iFrameId').style.height = contentHeight + 'px'; } 

然后将事件绑定到iFrame的onload事件(但是你想要):

“scrolling = auto”非常有用,以防大小调整失败,至少它们有滚动条。 如果iFrame重新加载,则会触发onload事件,因此如果他们单击其中的链接,则会很有用。

我对这个jQuery插件运气不错 – https://github.com/davidjbradshaw/iframe-resizer