我有一个包含文本的div,它只在某些情况下显示在另一个div中。这个HTML很简单,看起来像:
<div id='parent'>
<div id='child'>
Some text inside child div
</div>
</div>
样式看起来像:
#parent{ display:none; height:0px; }
使用jQuery我想获得孩子的高度,就像div在父母之外一样。
以下javascript返回0,我希望大约有15个。
var child_height = $('#child').height();
alert(child_height);
答案 0 :(得分:2)
尝试所有这些并且正常工作:
console.log($('#child').outerHeight());
console.log($('#child').css('height'));
console.log($('#child').height());
据你编辑:
var height = $('#parent').css({visibility: 'hidden', display : 'block'}).find('#child').height();
$('#parent').css({visibility: 'hidden', display: 'none'});
console.log(height);
<强> DEMO 强>
答案 1 :(得分:2)
您可以暂时显示隐藏的父母,然后在以下后隐藏它们:
// .parents means it will search through all parents, not just first hidden
var hiddenParents = $("#child").parents(":hidden").show();
var childHeight = $("#child").height();
hiddenParents.hide();
alert(childHeight);
答案 2 :(得分:1)
var child_height = $('#child').outerHeight();
alert(child_height);
虽然在FF 10上你的原始代码工作正常。
根据评论更新:
对于隐藏字段,它将返回零,您可以执行以下操作:
jQuery('#parent').css('display','block');
var child_height = $('#child').outerHeight();
alert(child_height);
child_height = $('#child').height();
alert(child_height);
jQuery('#parent').css('display','none');
答案 3 :(得分:1)
我注意到你说:“只在某些情况下显示另一个div内”。如果父div具有display: none;
(例如,如果您使用许多jQuery函数中的任何一个隐藏它,这将是最终的结果),那么子项的高度将返回为0。