例如:

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

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


当前回答

这适用于我(也与多个iframe在一个页面):

$('iframe').load(function(){$(this).height($(this).contents().outerHeight());});

其他回答

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

这是不工作的chrome。但是在firefox上工作。

以下是精简版:

<iframe src="hello.html" sandbox="allow-same-origin"
        onload="this.style.height=(this.contentWindow.document.body.scrollHeight+20)+'px';">
</iframe>

将此添加到<head>部分:

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

把你的iframe改成这样:

<iframe src="..." frameborder="0" scrolling="no" onload="resizeIframe(this)" />

在现场讨论中发现。

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

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

将这个添加到<head>标签:

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

并将以下onload属性添加到iframe,如下所示

<iframe onload='resizeIframe(this)'></iframe>

这适用于我(也与多个iframe在一个页面):

$('iframe').load(function(){$(this).height($(this).contents().outerHeight());});