How to get height of the highest children element in javascript/jQuery?

后端 未结 4 629
無奈伤痛
無奈伤痛 2020-12-05 05:10

I need a function to get the height of the highest element inside a div.

I have an element with many others inside (dynamically generated), and when I ask for the he

相关标签:
4条回答
  • 2020-12-05 05:33

    I found this snippet which seems more straight forward and shorter at 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);
    
    0 讨论(0)
  • 2020-12-05 05:37

    If the div element is smaller than it's children, the children are probably floating. Can you allow the div to be as large as children?

    If you can, add a clearing element at the bottom to make the div wrap it's children:

    <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>
    

    Or apply a clearfix CSS solution to do pretty much the same thing but without extra markup or a clearing div.

    The containing div will then get the same height as the highest child element, and you can get it by:

    $("#someParent").height();
    
    0 讨论(0)
  • 2020-12-05 05:43

    In my case I had to use it with a responsive design so I made it work with window 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');
    });
    

    I hope this will help someone !

    Happy coding guys ! :)

    0 讨论(0)
  • 2020-12-05 05:49

    You could always do:

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

    Edited to make it work again.

    0 讨论(0)
提交回复
热议问题