javascript - 添加加载后调整 iframe 的大小

标签 javascript html dom iframe frame

在使用 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/

相关文章:

javascript - 如何使用 javascript 从 cookie 中创建和读取值?

javascript - 当用户单击按钮时运行函数?

html - 2 个不同的 div 从同一点开始。为什么第二个不在另一个下面?

javascript - Array.prototype.slice shim 用于旧版 Internet Explorer 中的非数组

javascript - 使用 JS 在可内容编辑的 div 中设置光标在 Chrome 中工作正常,但如果 div 为空则不行

javascript - 当网络处于后台时如何使背景音频暂停

javascript - 查询 dynamodb shell 中的最后 10 个项目

javascript - 操作 mongodb 查询中的列表

css - 防止 child (span)在字/行中间溢出(CSS/HTML)

javascript - 如何在 javascript 中的 element.setAttribute 中以 DOM 中的百分比形式传递参数?