2011-05-30 95 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);