在使用 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 的高度?
*编辑**
可能的解决方法:
有没有希望我可以使用 Access-Control-Allow-Origin 来解决这个问题?假设进入 iframe 的页面是我自己的,或者是从 php 脚本回显的
最佳答案
我使用以下函数将 iframe 的大小调整为内容的高度。它适用于 Intranet 应用程序(并且仅在 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/