在使用javascript加载iframe后,我在调整其大小时遇到问题。我使用的设置宽度约为300px,工作良好,但动态地将iframe的高度调整为其内容的大小(博客文章)。
我尝试过让contentWindow(没有子dom元素)和contentDocument(未定义)无效。
我是在装货时做的:
var iframe = document.createElement('iframe');
iframe.setAttribute('id','postFrame');
iframe.setAttribute('frameborder','no');
iframe.setAttribute('scrolling','no');
iframe.setAttribute('onload','resizeFrame();');
iframe.setAttribute('width','300px');
iframe.setAttribute('src','http://espn.go.com/espn/print?id=7454651');
var container = document.getElementById('container');
container.appendChild(iframe);
function resizeFrame(){ /* resize iframe based on content height*/ }
是否有方法根据iframe中的内容重新调整iframe的高度?
*编辑**
可能的解决方法:
是否有任何希望,我可以使用访问控制允许起源来协助问题?假设iframe中的页面是我自己的,或者是来自php脚本的回声
最佳答案
我使用以下函数将iframe调整为内容的高度。它是为一个内部网应用程序(并且只在IE8中正确测试)而设计的,但它确实可以工作,因此它可能会提供丢失的线索-
function sizeIframeToContent(id) {
// resize iframe to be the height of the content
try {
var frame = document.getElementById(id);
innerDoc = (frame.contentDocument) ?
frame.contentDocument : frame.contentWindow.document;
var objToResize = (frame.style) ? frame.style : frame;
objToResize.height = innerDoc.body.scrollHeight + 10 + 'px';
//objToResize.width = innerDoc.body.scrollWidth + 10 + 'px';
}
catch (err) {
console.log(err.message);
}
}
编辑说明-加载文档后,您应该能够找到文档高度,然后可以将其用作iframe的高度。我评论了上面函数的宽度部分,因为您特别询问了高度。
关于javascript - 加载后调整iframe的大小,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8843060/