如何获得javascript / jQuery中最高的子元素的高度?

我需要一个函数来获取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-tricks.com/snippets/jquery/equalize-heights-of-divs看起来更直接更短

 var maxHeight = 0; $(yourelemselector).each(function(){ var thisH = $(this).height(); if (thisH > maxHeight) { maxHeight = thisH; } }); $(yourelemselector).height(maxHeight); 

如果div元素小于它的子元素,则子元素可能是浮动的。 你可以让div和孩子一样大吗?

如果可以的话,在底部添加一个清除元素,使div包装它的子项:

 

test

test1 test2

或者应用clearfix CSS解决方案做几乎相同的事情,但没有额外的标记或清除div。

然后,包含div将获得与最高子元素相同的高度,您可以通过以下方式获取它:

 $("#someParent").height(); 

在我的情况下,我不得不使用它与响应式设计,所以我使用窗口resize。

 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'); }); 

我希望这会对某人有所帮助!

快乐的编码家伙! 🙂