如何获得最高的儿童元素的高度在JavaScript / jQuery的?
-
21-08-2019 - |
题
我需要一个函数来获得一个div内的最高元件的高度。
我有内部(动态生成的)配有许多其他的元素,并且当我要求的容器元素的使用$(ELEM).height()的高度,我得到比一些它里面的内容更小的高度。 一些元件的内部是大于该元素表示为具有尺寸更大的图像。
我需要知道的最高的元素,所以我可以得到它的高度。
解决方案
您总是可以做:
var t=0; // the height of the highest element (after the function runs)
var t_elem; // the highest element (after the function runs)
$("*",elem).each(function () {
$this = $(this);
if ( $this.outerHeight() > t ) {
t_elem=this;
t=$this.outerHeight();
}
});
编辑,以使其重新工作。
其他提示
我发现这个片段似乎更直接和更短的的http:// CSS-技巧的.com /片段/ jquery的/均衡-高度-的-div的
var maxHeight = 0;
$(yourelemselector).each(function(){
var thisH = $(this).height();
if (thisH > maxHeight) { maxHeight = thisH; }
});
$(yourelemselector).height(maxHeight);
如果div元素是比它更小的孩子,孩子们可能浮动。你可以让DIV是儿童大?
如果可以的话,在底部添加一个清除元件使包装DIV其子:
<div id="someParent">
<p>test</p>
<img src="test1.png" alt="test1" style="float: left" />
<img src="test2.png" alt="test2" style="float: left" />
<div style="clear: both;"></div>
</div>
或应用 clearfix CSS的解决方案几乎做同样的事情但没有额外的标记或结算div中。
包含div会再拿到相同的高度最高的子元素,你可以通过把它:
$("#someParent").height();
在我来说,我有一个负责任的设计,所以我把它与窗口大小调整工作中使用它。
function fixHeight(elem){
var maxHeight = 0;
$(elem).css('height','auto');
$(elem).each(function(){
if ($(this).height() > maxHeight) { maxHeight = $(this).height(); }
});
$(elem).height(maxHeight);
}
$(window).resize(function () {
fixHeight('.myelement');
});
$(document).ready(function(e) {
fixHeight('.myelement');
});
我希望这会帮助别人!
编码愉快的家伙! :)
不隶属于 StackOverflow