我正在加载一个iframe中的aspx网页。Iframe中的内容的高度可以大于Iframe的高度。iframe不应该有滚动条。

我在iframe里面有一个包装器div标签,基本上是所有的内容。我写了一些jQuery来实现调整大小:

$("#TB_window", window.parent.document).height($("body").height() + 50);

在哪里 TB_window是包含Iframe的div。

Body - iframe中aspx的Body标签。

该脚本附加到iframe内容。我从父页面获得TB_window元素。虽然这在Chrome上工作得很好,但在Firefox中TB_window崩溃了。我真的不明白为什么会发生这种情况。


当前回答

比起使用javscript/jquery,我发现最简单的方法是:

<iframe style=“min-height:98vh” src=“http://yourdomain.com” width=“100%”></iframe>

这里1vh =浏览器窗口高度的1%。所以要设置的高度理论值是100vh,但实际上是98vh。

其他回答

脚本

<script type="text/javascript" language="javascript">
    $(document).ready(function(){
        var height = $(window).height();
        $('.myIframe').css('height', height - 200);
    });
</script>

iframe

<iframe class="myIframe" width="100%"></iframe>

我的情况就是这样。

只需要将iframe容器的位置设置为绝对,iframe将根据其内容自动改变其高度

<style>
   .iframe-container {
       display: block;
       position: absolute;
       /*change position as you need*/
       bottom: 0;
       left: 0;
       right: 0;
       top: 0;
   }
   iframe {
       margin: 0;
       padding: 0;
       border: 0;
       width: 100%;
       background-color: #fff;
   }
 </style>
 <div class="iframe-container">
     <iframe src="http://iframesourcepage"></iframe>
 </div>

所有其他答案都是正确的,但如果iframe有一些动态内容,如稍后加载的地图,并动态更改iframe滚动高度。我就是这样做到的。

var iFrameID = document.getElementById('idIframe');

intval =  setInterval(function(){
if(iFrameID.scrollHeight == iFrameID.contentWindow.document.body.scrollHeight){
     clearInterval(intval);
}else{
   iFrameID.height = iFrameID.contentWindow.document.body.scrollHeight + "px";
  }
},500)

我只是将代码包装在setInterval内,它匹配iframe滚动高度与iframe内容滚动高度,然后清除间隔。

您可以通过使用以下方法检索IFRAME内容的高度: contentWindow.document.body.scrollHeight

加载IFRAME后,您可以通过以下操作更改高度:

<script type="text/javascript">
  function iframeLoaded() {
      var iFrameID = document.getElementById('idIframe');
      if(iFrameID) {
            // here you can make the height, I delete it first, then I make it again
            iFrameID.height = "";
            iFrameID.height = iFrameID.contentWindow.document.body.scrollHeight + "px";
      }   
  }
</script>   

然后,在IFRAME标记上,像这样连接处理程序:

<iframe id="idIframe" onload="iframeLoaded()" ...

我有一个情况在一段时间前,我还需要调用iframeLoaded从IFRAME本身的表单提交后发生。您可以通过在IFRAME的内容脚本中执行以下操作来实现这一点:

parent.iframeLoaded();

对蓝鱼的回答略有改进…

function resizeIframe(iframe) {
    var padding = 50;
    if (iframe.contentWindow.document.body.scrollHeight < (window.innerHeight - padding))
        iframe.height = iframe.contentWindow.document.body.scrollHeight + "px";
    else
        iframe.height = (window.innerHeight - padding) + "px";
}

这考虑了窗口屏幕(浏览器,手机)的高度,这对响应式设计和具有巨大高度的iframe很好。 填充表示你想要的iframe上方和下方的填充,在这种情况下它贯穿整个屏幕。