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

Lea*_*one 23 javascript jquery height dom

我需要一个函数来获得div中最高元素的高度.

我有一个元素,里面有许多其他元素(动态生成),当我使用$(elem).height()询问容器元素的高度时,我得到的高度比它里面的一些内容要小.内部的一些元素是大于该元素所具有的大小的图像.

我需要知道最高元素,所以我可以得到它的高度.

geb*_*eer 39

我在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);
Run Code Online (Sandbox Code Playgroud)


Tho*_*mas 31

你可以随时做:

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();
    }
});
Run Code Online (Sandbox Code Playgroud)

编辑再次使它工作.

  • 您可能希望使用outerHeight()而不是height(). (2认同)

old*_*ard 6

如果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>
Run Code Online (Sandbox Code Playgroud)

或应用clearfix CSS解决方案执行几乎相同的操作,但无需额外的标记或清除div。

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

$("#someParent").height();
Run Code Online (Sandbox Code Playgroud)


Cst*_*ves 6

就我而言,我必须将其与响应式设计一起使用,因此我使其与窗口大小调整一起使用。

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');
});
Run Code Online (Sandbox Code Playgroud)

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

祝大家编码愉快!:)