【问题标题】:Resize iframe after adding in on load添加加载后调整 iframe 大小
【发布时间】:2012-02-09 05:06:54
【问题描述】:

在使用 javascript 在加载时注入 iframe 后,我无法调整其大小。我使用了大约 300 像素的设置宽度,它可以正常工作,但动态地将 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 脚本中回显的

【问题讨论】:

  • 我假设你没有 'espn.go.com',在这种情况下,我在这几个月里在这方面做了很多工作 - 它依赖于“客户”和“供应商”(您将是其中之一,espn.go.com 将是另一个)。我认为你最好私下联系我,这样我就可以在 Skype 上与你交谈。如果您在此处留下您的 Skype 用户名,那么我将添加您并尽力提供帮助。

标签: javascript html dom iframe frame


【解决方案1】:

我使用以下函数将 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 的高度。当您特别询问高度时,我评论了上述函数的宽度部分。

【讨论】:

  • 我在控制台中得到这个:无法读取未定义的属性“正文”
  • @buffstar24 在 Chrome 中也能做到这一点……看看我能做什么
  • 而在 Firefox 中,我得到了 的权限被拒绝以获取属性 HTMLDocument.body
  • @buffstar24 我认为这是本地权限问题。使用 Chrome 开发者工具并进入,您可以看到属性,但它没有提供访问权限...
  • @buffstar24 我使用 Visual Studio Web 服务器来运行代码,它运行良好……但是当不通过 Web 服务器运行时,它在 Chrome 中无法运行
猜你喜欢
  • 1970-01-01
  • 2010-10-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-23
相关资源
最近更新 更多