2011-05-30 94 views

回答

6

暫時show()荷蘭國際集團檢索孩子的身高元素似乎工作確定。

HTML:

<div id="target" style="display:none;"> 
    <!-- Add a background color to see if it's noticeable --> 
    <div style="height:123px; background:#000;"></div> 
</div> 

JS:

// Show the hidden parent of the element we want the height of 
$("#target").show(0, function(){ 
    // Find and grab the height of the element we want 
    the_height = $(this).find("div").height(); 
// Hide parent and display child's height after it 
}).hide().after(the_height); 

演示:jsfiddle.net/Gts6A/72

+3

+1爲一個很好的技巧...但顯示和隱藏div將導致眨眼效果。 – Vivek 2011-05-30 12:05:41

+0

@Vivek:好像不適合我。 – Marcel 2011-05-30 12:09:18

+0

這肯定會導致瀏覽器在舊PC上閃爍。這是因爲它會強制連續兩次完成重新佈局。我建議在依靠它之前徹底測試此解決方案。 – Exelian 2011-05-30 12:29:12

1

it's very difficult(in other word you can't)獲取隱藏元素的高度...因爲dom doesn't consider hidden elements while rendering the page

1

隱藏的元素具有未定義的寬度和高度,因此無法獲取它們。

2

你可以這樣做,或者你可以使用這個question的破解。

$("#target").parent().show(); 
var h = $("#target").height(); 
$("#target").parent().hide(); 
alert(h); 

參見fiddle

+0

+1爲問題的鏈接(和所有黑客) – mc10 2011-05-30 16:50:37

0

要麼你應該顯示div或不可能獲得隱藏元素的高度。我會說,使用.show()來顯示div,獲得高度,然後使用.hide()來再次隱藏它。

1

這是有點klunky,但你必須有一個對象之前,它可以呈現被測量。

var $target = $("#target"); 

$target[0].parentNode.runtimeStyle.display = "block"; 
var height = $target.height(); 
$target[0].parentNode.runtimeStyle.display = "none"; 
alert(height);