例如:

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

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


当前回答

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)”

其他回答

jq2('#stocks_iframe').load(function(){
var iframe_width = jq2('#stocks_iframe').contents().outerHeight() ; 
jq2('#stocks_iframe').css('height',iframe_width); });

<iframe id='stocks_iframe' style='width:100%;height:0px;' frameborder='0'>

这对我来说很有效(大多数情况下)。

把这个放在你的页面底部。

<script type="application/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>

<script type="application/javascript" src="/script/jquery.browser.js">
</script>

<script type="application/javascript" src="/script/jquery-iframe-auto-height.js">
</script>

<script type="application/javascript"> 
  jQuery('iframe').iframeAutoHeight();
  $(window).load(
      function() {
          jQuery('iframe').iframeAutoHeight();  
      }
  );

  // for when content is not html e.g. a PDF
  function setIframeHeight() {
      $('.iframe_fullHeight').each(
          function (i, item) {
              item.height = $(document).height();
          }
      );
  };

  $(document).ready( function () {
      setIframeHeight();
  });
  $(window).resize( function () {
      setIframeHeight();
  });
</script> 

前半部分来自??,当iframe中有HTML时才生效。 当iframes类为iframe_fullHeight时,后半部分将iframe设置为页面高度(而不是内容高度)。如果内容是PDF或其他类似的,您可以使用这个,但您必须设置类。也只能使用时,全高度是适当的。

注意:由于某些原因,当它在调整窗口大小后重新计算时,它得到了错误的高度。

我在过去调用iframe时遇到过问题。onload用于动态创建iframe,所以我用这种方法来设置iframe大小:

iFrame视图

var height = $("body").outerHeight();
parent.SetIFrameHeight(height);

主要的观点

SetIFrameHeight = function(height) {
    $("#iFrameWrapper").height(height);
}

(这只会工作,如果两个视图在同一个域)

避免使用内联JavaScript;你可以使用一个类:

<iframe src="..." frameborder="0" scrolling="auto" class="iframe-full-height"></iframe>

用jQuery引用它:

$('.iframe-full-height').on('load', function(){
    this.style.height=this.contentDocument.body.scrollHeight +'px';
});

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

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

他们也是一个React版本。

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

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