如何设置iframe高度以适应内容?

hel*_*one 5 html javascript iframe jquery

我想从Iframe中删除滚动条.当我手动设置Iframe的高度时它可以工作,但Iframe大小可以改变,我不知道如何在页面加载时获得Iframe高度.

有没有办法删除滚动条并适合iframe内容?

<div class="portlet" id="pageContainer">
    <iframe id="frame" width="100%" frameborder="0" height="2000" scrolling="false" allowfullscreen="" src="/app/mytestapp" style="overflow: hidden"></iframe>
</div>
Run Code Online (Sandbox Code Playgroud)

当我尝试低于功能时,它不会返回正确的高度.(它返回2000px,但我的Iframe高度接近3000px)

$('iframe').load(function() {        
    this.contentWindow.document.body.offsetHeight + 'px';
});
Run Code Online (Sandbox Code Playgroud)

Pan*_*het 0

使用此参数删除边框和滚动条

scrolling="no"
frameborder="no"
Run Code Online (Sandbox Code Playgroud)

这段代码用于设置 iframe 高度

var width = $(window).width()
var height = $(window).height()

$('#frame').css({ width : width, height : height })
Run Code Online (Sandbox Code Playgroud)

如果您需要动态更改高度以适应窗口大小,请将上面的代码包装到函数中并在resize事件 at上使用它,还可以像这样window调用文档的事件:ready

function iframeResize(){

    var width = $(window).width()
    var height = $(window).height()

    $('#frame').css({ width : width, height : height })
}

$(window).on('resize', iframeResize)
$(document).on('ready', iframeResize)
Run Code Online (Sandbox Code Playgroud)

更新

此外,您还需要在 iframe 的父页面上保留边距和填充。默认值会导致父页面出现滚动条。如果您不需要在页面上携带除 iframe 之外的其他元素,这样的解决方案将是一个简单的解决方案。

* {
    margin: 0;
    padding: 0;
}
Run Code Online (Sandbox Code Playgroud)