【问题标题】:content height of hidden iframe隐藏 iframe 的内容高度
【发布时间】:2016-01-02 13:45:39
【问题描述】:

正如标题所说,我正在尝试设置一个隐藏的 iframe 高度以匹配它的内容,但我一直得到非常不正确的高度。

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

我一直在使用可以轻松看到很长时间的框架来执行此操作,但现在这些框架在加载时是隐藏的,它正在发挥作用。我浏览了 SO 的每个角落,尝试了很多基本功能的变体,但没有运气。

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

对 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 :(
});

【问题讨论】:

  • 尝试使用style="visibility:hidden;" 而不是display:none;。这将使 iframe 呈现为好像它具有布局一样,因此您的高度/宽度计算应该是准确的。
  • 谢谢,我会试一试。可见性是否适用于 ie8?
  • 是的,多年来它一直是 CSS 规范的一部分。它甚至适用于 IE6 :)
  • 完美!结合使用可见性和显示无,我能够完全达到我想要的结果!谢谢。

标签: javascript iframe height


【解决方案1】:

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

我使用了 display 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,并设置 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);
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-25
    • 2016-06-17
    • 2013-08-02
    • 2012-10-28
    • 2020-08-05
    相关资源
    最近更新 更多