隐藏 iframe 的内容高度

xxs*_*nxo 5 javascript iframe height

就像标题所说,我正在尝试设置隐藏的 iframe 高度以匹配其内容,但我不断得到非常不正确的高度。

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

我一直在轻松地使用长时间可见的框架来执行此操作,但现在框架在加载时被隐藏,它正在发挥作用。我已经检查了 SO 的每个角落,并尝试了基本功能的许多变体,但没有运气。

我尝试让 iframe 保持可见,设置高度然后隐藏它,但是框架的快速闪烁没有吸引力。有没有一种我不知道的方法可以从隐藏的 iframe 获取实际内容高度?

接受 jquery 或普通 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 :(
});
Run Code Online (Sandbox Code Playgroud)

xxs*_*nxo 1

根据 @murdock 的建议,我能够通过可见性和显示样式的组合来实现我正在寻找的结果。

我使用了 display attr after 因为即使有可见性,父主体的高度也会增加,除非该元素设置为 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);
});
Run Code Online (Sandbox Code Playgroud)

希望这对将来的其他人有帮助。

编辑:起初我仍然感到相当多的页面退缩。所以我删除了可见性样式并决定在我的 css 中将高度设置为 0px。然后我获取内容高度,隐藏 iframe,并设置 iframe 高度以匹配内容。糟糕!

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);
});
Run Code Online (Sandbox Code Playgroud)