iframe不会动态调整大小

时间:2013-04-14 00:23:06

标签: javascript jquery html iframe

这已被问过很多次,但我问,因为没有解决方案对我有用,而且我找不到很多正确的解决方案。我想要一个静态宽度,但是基于内部内容的动态高度。

我正在子域上托管博客,并通过iframe将其插入我的主域名中的页面。我可以设置一个静态高度并滚动,以便用户仍然可以使用博客,但我想要一些看起来更好的东西。当我发布新帖子或用户点击评论部分时,我希望iframe能够自动调整大小,以便它可以显示所有内容而无需滚动条。

到目前为止,我还没有找到有效的解决方案,主要是因为许多涉及同一域的网页。

2 个答案:

答案 0 :(得分:2)

由于您可以控制iframe中的内容,因此可以尝试窗口message事件。

将此添加到您的框架内容:

// post a message to the top window with information about the height
window.onload = function(){
    top.postMessage(document.body.scrollHeight, '*');
}

这是包含iframe的页面:

// listen for the message and set the iframe height when it arrives
window.addEventListener( "message", function(event){
    document.getElementById('test').style.height = event.data+'px';
}, false);

<iframe id="test" src="test.html"/>

回应你的评论。以下是iframe内容更改时更新iframe高度的一些方法。

1。 Mutation Events

// listen to all descendants of the body and if there are any modifications, post an update to the top window 
document.body.addEventListener("DOMSubtreeModified", function(){
    top.postMessage(document.body.scrollHeight, '*');
}, false);

这种方法已被折旧。这是替代品,但尚未完全支持:

2。 Mutation Observers

// create a MutationObserver to listen for modification to the body and post an update to the top window
var observer = new MutationObserver(function(){
    top.postMessage(document.body.scrollHeight, '*');
});
observer.observe(document.body, {childList: true, subtree: true});

我会选择第一个选项,直到第二个选项得到更好的支持

答案 1 :(得分:0)

我想补充一点, offsetHeight scrollHeight 更可靠,可以计算出iFrame的大小。只要将body margin设置为0.问题是ScrollHeight只会增加页面的大小,而不是减少它。保证金问题can be overcome,但如果你关心 IE8 ,那就是很多代码。

MutationEvents死了,使用 MutationObserver 。虽然它在IE10及以下版本中不起作用,但您必须回退到 setInterval ,如果您不想要用户,则应使用 32 的计时器看到任何屏幕闪烁。 RequestAnimationFrame 也有助于减少屏幕闪烁。

您可能有兴趣查看处理所有这些问题的https://github.com/davidjbradshaw/iframe-resizer

相关问题