【问题标题】:How to set iframe height to fit content?如何设置 iframe 高度以适应内容?
【发布时间】:2017-01-13 17:50:09
【问题描述】:

我正在尝试从 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>

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

$('iframe').load(function() {        
    this.contentWindow.document.body.offsetHeight + 'px';
});

【问题讨论】:

  • 这一行没有目的:this.contentWindow.document.body.offsetHeight + 'px'; .尝试 height="2000px" 。可能溢出:隐藏使内容 iframe 的 px 不可见。

标签: javascript jquery html iframe


【解决方案1】:

你可以使用

$('iframe').load(function() {
    $('#frame').height($('#frame').get(0).contentWindow.document.body.offsetHeight + 'px');
})

$('iframe').load(function() {
    setTimeout(function(){
        $('#frame').height($('#frame').get(0).contentWindow.document.body.offsetHeight + 'px');
    }, 3000);
})

【讨论】:

  • 已经告知此代码不会返回 Iframe 的内容高度。
  • @hellzone 如果你在settimeout 函数中调用它肯定会起作用
  • 还是不行。它仍然返回我的自定义 Iframe 高度(2000px),但不返回 Iframe 的内容高度。
  • 如果iframe的高度设置为2000px,内容只需要400pxscrollHeight会返回2000px。 IE。 scrollHeight 如果大于内容高度,则返回当前高度。为避免这种情况,请将 iframe 的高度设置为 1px ;然后scrollHeight 将返回内容高度。
【解决方案2】:

使用该参数去除边框和滚动条

scrolling="no"
frameborder="no"

这个设置 iframe 高度的代码

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

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

如果您需要动态更改高度以适应窗口大小,请将上面的代码包装到函数中并在windowresize 事件上使用它,也可以像这样调用文档的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)

更新

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

* {
    margin: 0;
    padding: 0;
}

【讨论】:

  • 它不工作。 $(window).height() 返回我的自定义 Iframe 高度,即 2000px,我仍然可以看到 Iframe 滚动条。
  • 您想在 iframe 内部还是外部使用此代码?
  • $(window).height() 返回视口的高度,所以我理解您的问题,例如您需要将 iframe 调整为父视口的大小
  • 我有一个 iframe,我想用这个 iframe 展示一些网站。该网站的高度为 3000 像素。我想要做的是用没有滚动条的 iframe 显示这个网站。
  • 好的,看来您需要调整 iframe 的大小以适应其内容。这个问题在那里解释 - stackoverflow.com/questions/819416/…
猜你喜欢
  • 2016-06-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-12
  • 2013-10-16
  • 1970-01-01
相关资源
最近更新 更多