2012-01-12 71 views
2

我在使用javascript在加载时注入iframe的大小时遇到​​问题。我使用大约300px的设置宽度,这很好,但动态地将iframe的高度调整为其内容大小(博客文章)。在加载后调整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脚本的echo'd

+0

我假设你不拥有'espn.go.com',在这种情况下,我在这几个月的工作中做了很多工作 - 它依赖于'客户'和' 'supplier'(你会是其中之一,espn.go.com会是其中一个)。如果你私下联系我,我认为最好,所以我可以通过Skype与你谈谈。如果您将Skype用户名留在此处,我会添加您并尝试提供帮助。 – ClarkeyBoy 2012-01-12 23:23:31

+0

嗯我不使用skype – mbuff24 2012-01-13 01:19:29

回答

1

我使用以下函数将iframe的大小调整为内容的高度。它是企业内部网应用程序(只有在IE8正确的测试),但可以肯定的作品,所以可能提供缺少的clue-

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); 
    } 
} 

编辑的explanation-一旦文件已加载,你应该能够找到这个文件然后您可以使用它作为iframe的高度。当你特别询问高度时,我评论了上述函数的宽度部分。

+0

我在控制台得到这个:无法读取属性'身体'的undefined – mbuff24 2012-01-12 23:27:05

+0

@ buffstar24在Chrome中得到这个以及...将看我能做些什么 – davidsleeps 2012-01-12 23:27:51

+0

而在Firefox中我获得许可拒绝 get property HTMLDocument.body – mbuff24 2012-01-12 23:39:36