0

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

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

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

4

2 回答 2

2

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

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

// 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. 突变事件

// 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. 突变观察者

// 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});

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

于 2013-04-14T01:01:35.053 回答
0

只是想我会补充一点,offsetHeightscrollHeight更可靠,用于计算 iFrame 的大小。只要将正文边距设置为 0。问题是 ScrollHeight 只会增加页面的大小,不会减小它。可以克服边距问题,但是如果您关心IE8 ,则代码量很大。

MutationEvents 已死,请使用MutationObserver。虽然它在 IE10 及更低版本中不起作用,但您必须退回到setInterval ,如果您不希望用户看到任何屏幕闪烁,您应该使用32的计时器。RequestAnimationFrame也有助于消除屏幕闪烁。

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

于 2014-03-21T23:56:00.597 回答