2015-10-05 149 views
3

就像標題所說,我試圖設置一個隱藏的iframes高度來匹配它的內容,但我一直得到非常不正確的高度。隱藏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 :(
}); 
+2

嘗試使用'style =「visibility:hidden;」'而不是'display:none;''。這將呈現iframe,就像它有佈局一樣,所以你的高度/寬度計算應該是準確的。 – murdock

+0

謝謝,我會給它一個鏡頭。可見度是否與ie8一起工作? – xxstevenxo

+0

是的,它已經成爲CSS規範多年的一部分。它甚至適用於IE6 :) – murdock

回答

1

Per @ 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,並設置了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); 
});