首页 文章

隐藏iframe的内容高度

提问于
浏览
4

就像 Headers 所说我试图设置一个隐藏的iframes高度以匹配它的内容,但我一直得到非常不正确的高度 .

我正在使用内容预加载新的(隐藏的)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 :(
});

1 回答

  • 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);
    });
    

    希望这有助于将来的其他人 .

    EDIT: 起初,我的页面还是有点退缩 . 所以我删除了可见性样式,并决定在我的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);
    });
    

相关问题