jQuery Equal Height Divs

前端 未结 3 850
执念已碎
执念已碎 2020-12-06 13:50

If i have the following markup;

One
two
three
相关标签:
3条回答
  • 2020-12-06 14:26

    Why not just use a table?

    Imho, doing layout in javascript like this is far more evil than doing the layout via tables. What happens if the user resizes their browser? You have to capture the resize event, but then you get a certain laggyness when resizing that makes your website look unpolished.

    0 讨论(0)
  • 2020-12-06 14:35
    <div id='parentDiv'>
      <div>
          <div id='sameHeight'>One<br>two<br>three</div>
          <div id='sameHeight'>four</div>
          <div id='sameHeight'>five</div>        
      <div>
      <div>
          <div id='sameHeight'>four</div>
          <div id='sameHeight'>six</div>
          <div id='sameHeight'>seven<br>eight</div>
      <div>
    </div>
    

    and in JavaScript using jQuery write :

    $(document).ready(function () {    
        $("div.parentDiv div div.sameHeight").css({ height: "100px" });
    });
    
    0 讨论(0)
  • 2020-12-06 14:45

    Firstly, you are probably aware only one element should have any one id attribute. So I have changed the selectors as if they were classes to classes below. Even though you may not give a care about W3C standards, browsers or JavaScript API, etc may rely on this behaviour and not work now or in the future.

       $(document).ready(function () {    
            $('div.parentDiv > div').each(function() {
    
            var $sameHeightChildren = $(this).find('.sameHeight');
            var maxHeight = 0;
    
            $sameHeightChildren.each(function() {
                maxHeight = Math.max(maxHeight, $(this).outerHeight());
            });
    
            $sameHeightChildren.css({ height: maxHeight + 'px' });
    
    
        });
    });
    

    Note: If you want them all to be the same height despite their parent div, this is what you want.

    $(document).ready(function () {    
            var $sameHeightDivs = $('.sameHeight');
            var maxHeight = 0;
            $sameHeightDivs.each(function() {
    
                maxHeight = Math.max(maxHeight, $(this).outerHeight());
    
            });
    
            $sameHeightDivs.css({ height: maxHeight + 'px' });
    });
    

    This will set them to all be the height of the tallest, per parent div element.

    Also, this answer may show you some other options.

    Note too that if the content inside changes again (perhaps via JavaScript), you will need to call this again, or put it in a setInterval() which I do not recommend.

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