让iframe根据内容自动调整高度而不使用滚动条?

比如说。

<iframe name="Stack" src="http://stackoverflow.com/" width="740"
        frameborder="0" scrolling="no" id="iframe"> ...
</iframe>

我希望它能够根据里面的内容来调整高度,而不使用滚动。

解决办法

将此添加到你的``部分。

<script>
  function resizeIframe(obj) {
    obj.style.height = obj.contentWindow.document.body.scrollHeight + 'px';
  }
</script>

并将你的iframe改为这样。

正如在sitepoint讨论上发现的那样。

评论(31)

hjpotter92的建议在Safari中不起作用! 我对脚本做了一个小的调整,所以现在它在Safari中也能工作。

唯一的变化是在每次加载时将高度重置为0,以便使一些浏览器能够降低高度。

把这个添加到``标签。

<script type="text/javascript">
  function resizeIframe(obj){
     obj.style.height = 0;
     obj.style.height = obj.contentWindow.document.body.scrollHeight + 'px';
  }
</script>

并在你的iframe中添加以下onload属性,像这样

评论(7)
function autoResize(id){
    var newheight;
    var newwidth;

    if(document.getElementById){
        newheight=document.getElementById(id).contentWindow.document.body.scrollHeight;
        newwidth=document.getElementById(id).contentWindow.document.body.scrollWidth;
    }

    document.getElementById(id).height=(newheight) + "px";
    document.getElementById(id).width=(newwidth) + "px"; 
}

将此添加到你的iframe中。 onload="autoResize('youriframeid')"

评论(0)