隐藏iframe的内容高度

时间:2015-10-05 19:32:50

标签: javascript iframe height

就像标题所说,我试图设置一个隐藏的iframe高度以匹配它的内容,但我的高度一直不正确。

我正在使用内容预加载新的(隐藏的)iframe,我需要在将iframe设置为由用户显示之前设置高度。

我一直在使用可以轻松看到很长时间的帧,但现在这些帧在加载时会被隐藏起来。我已经浏览了SO的每个角落,尝试了很多基本功能,但没有运气。

我试着让iframe可见,设置高度然后隐藏它,但框架的快速闪光没有吸引力。有没有一种方法我只是不知道从隐藏的iframe获取ACTUAL内容高度?

打开jquery或plain js的想法。以下是我一直在使用的两个最常见的例子。

对此的任何建议将不胜感激。提前谢谢。

// example 1 
function resizeIframe(obj){
    obj.style.height = 0;
    obj.style.height = obj.contentWindow.document.body.scrollHeight + 'px';
}

portalDiv.append('<iframe src="" scrolling="no" style="display:none;"></iframe>');
$('iframe').last().attr('src', '/content.php').load(function() {
    resizeIframe(this);
    // should return 363px
    // returns 1531px :(
});

// example 2
portalDiv.append('<iframe src="" scrolling="no" style="display:none;"></iframe>');
$('iframe').last().attr('src', '/content.php').load(function() {
    var contentHeight = $(this).contents().find(".container").height();
    $(this).height(contentHeight+"px")
    // should return 363px
    // returns 1531px :(
});

1 个答案:

答案 0 :(得分:1)

Per @ murdock的建议我能够通过可见性和显示风格的组合来实现我所寻求的结果。

之后我使用了显示attr,因为即使有可见性,父体的高度也会增加,除非元素设置为display:none;

这就是我做的事情

portalDiv.append('<iframe src="" scrolling="no" style="visibility:hidden;"></iframe>');
$('iframe').last().attr('src', '/content.php').load(function() {
   var contentHeight = ($(this).contents().find(".question-table-container").height()+30);
   $(this).removeAttr("style").hide().height(contentHeight);
});

希望将来可以帮助其他人。

编辑:起初,我的页面还是有点畏缩。所以我删除了可见性样式,并决定在我的CSS中将高度设置为0px。然后我获得内容高度,隐藏iframe,并设置iframes高度以匹配内容。祸不单行!

portalDiv.append('<iframe src="" scrolling="no" style="visibility:hidden;"></iframe>');
$('iframe').last().attr('src', '/content.php').load(function() {
   var contentHeight = this.contentWindow.document.body.scrollHeight;
   $(this).hide().height(contentHeight);
});
相关问题