我正在加载一个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崩溃了。我真的不明白为什么会发生这种情况。


当前回答

我发现特洛伊的答案不管用。这是为ajax重新编写的相同代码:

$.ajax({                                      
    url: 'data.php',    
    dataType: 'json',                             

    success: function(data)
    {
        // Put the data onto the page

        // Resize the iframe
        var iframe = $(window.top.document).find("#iframe");
        iframe.height( iframe[0].contentDocument.body.scrollHeight+'px' );
    }
});

其他回答

示例使用PHP htmlspecialchars() +检查高度是否存在,并为> 0:

$my_html_markup = ''; // Insert here HTML markup with CSS, JS... '<html><head></head><body>...</body></html>'
$iframe = '<iframe onload="if(this.contentWindow.document.body.scrollHeight) {this.height = this.contentWindow.document.body.scrollHeight;}" width="100%" src="javascript: \''. htmlspecialchars($my_html_markup) . '\'"></iframe>';

我使用jQuery和下面的代码为我工作,

var iframe = $(window.top.document).find("#iframe_id_here");
iframe.height(iframe.contents().height()+'px' );

把这个添加到iframe中,这对我来说很管用:

onload="this.height=this.contentWindow.document.body.scrollHeight;"

如果你使用jQuery,试试下面的代码:

onload="$(this).height($(this.contentWindow.document.body).find(\'div\').first().height());"

只需要将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>

简单的解决方案是测量内容区域的宽度和高度,然后使用这些测量值来计算底部填充百分比。

在本例中,测量值为1680 x 720 px,因此底部的填充为720 / 1680 = 0.43 * 100,结果为43%。

.canvas-container {    
    position: relative;
    padding-bottom: 43%; // (720 ÷ 1680 = 0.4286 = 43%)
    height: 0;
    overflow: hidden;   
}

.canvas-container iframe {    
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;   
}