例如:

<iframe name="Stack" src="http://stackoverflow.com/" width="740"
        frameborder="0" scrolling="no" id="iframe"> ...
</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)" />

在现场讨论中发现。

其他回答

以下是精简版:

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

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

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

在IE11上试试这个

<iframe name="Stack" src="http://stackoverflow.com/" style='height: 100%; width: 100%;' frameborder="0" scrolling="no" id="iframe">...</iframe>

jQuery的.contents()方法允许我们在DOM树中搜索元素的直接子元素。

jQuery:

$('iframe').height( $('iframe').contents().outerHeight() );

记住,在iframe内的页面主体必须有它的高度

CSS:

body {
  height: auto;
  overflow: auto
}

您可以使用这个库,它既能正确地调整iframe的初始大小,也能通过检测iframe内容的大小变化(通过setInterval中的常规检查或通过MutationObserver)并调整它来保持它在正确的大小。

https://github.com/davidjbradshaw/iframe-resizer

他们也是一个React版本。

https://github.com/davidjbradshaw/iframe-resizer-react

这适用于交叉和相同域的iframe。