由于您可以控制 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});
我会选择第一个选项,直到第二个得到更好的支持