【问题标题】:Setting equal heights for div's with jQuery使用 jQuery 为 div 设置相等的高度
【发布时间】:2012-07-26 03:48:03
【问题描述】:

我想用 jQuery 为 div 设置相等的高度。 所有的 div 可能有不同的内容量和不同的默认高度。这是我的 html 布局示例:

<div class="container">
    <div class="column">This is<br />the highest<br />column</div>
    <div class="column">One line</div>
    <div class="column">Two<br />lines</div>
</div>
<div class="container">
    <div class="column">One line</div>
    <div class="column">Two<br>lines</div>
    <div class="column">One line</div>
</div>

我正在使用下一个 jQuery 函数设置高度:

$(document).ready(function(){

    var highestBox = 0;
        $('.container .column').each(function(){  
                if($(this).height() > highestBox){  
                highestBox = $(this).height();  
        }
    });    
    $('.container .column').height(highestBox);

});

这很好用,但在我的情况下不行,因为我希望所有“列”仅在一个“容器”内相等。这意味着在第一个容器中,所有框必须与第一个 div 一样高,但在第二个容器中,它们必须等于第二列。

所以问题是——我应该如何修改我的 jQuery 来达到这个目的?

谢谢!

【问题讨论】:

    标签: jquery html height equals


    【解决方案1】:

    回答您的具体问题

    您的代码正在检查任何容器中的所有列,您需要做的是:

    • 循环遍历每个容器
      • 获取该容器内每一列的高度
      • 找到最高的一个
      • 在移动到下一列之前,将该高度应用于该容器中的每一列。

    注意:尝试提供一个示例 jsfiddle 您的问题,它使我们能够 为了更轻松地帮助您和理解问题,您可以查看 立即工作的解决方案,它鼓励更快的响应。

    快速(粗略)示例

    $(document).ready(function(){
    
        // Select and loop the container element of the elements you want to equalise
        $('.container').each(function(){  
          
          // Cache the highest
          var highestBox = 0;
          
          // Select and loop the elements you want to equalise
          $('.column', this).each(function(){
            
            // If this box is higher than the cached highest then store it
            if($(this).height() > highestBox) {
              highestBox = $(this).height(); 
            }
          
          });  
                
          // Set the height of all those children to whichever was highest 
          $('.column',this).height(highestBox);
                        
        }); 
    
    });
    .container { border 1px solid red; }
    .column { border: 1px solid blue; float:left; width: 30%; text-align:center; }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    
    <div class="container">
        <div class="column">This is<br />the highest<br />column</div>
        <div class="column">One line</div>
        <div class="column">Two<br />lines</div>
    </div>
    <div class="container">
        <div class="column">One line</div>
        <div class="column">Two<br>lines</div>
        <div class="column">One line</div>
    </div>


    图书馆!

    这是我发现的一个库,如果你想要更多的话,它看起来很有希望 巧妙的均衡控制

    http://brm.io/jquery-match-height-demo/



    解决@Mem 的问题

    问题:如果您有需要加载的图像又会修改容器的高度,$(document).ready() 会起作用吗?


    图片加载后均衡高度

    如果您正在加载图像,您会发现此解决方案并不总是有效。这是因为document.ready is fired at the earliest possible time,也就是说它不会等待外部资源(例如图片)加载进来。

    当您的图像最终加载时,它们可能会在均衡脚本运行后扭曲其容器的高度,导致它看起来也不太工作。


    用图像解决等高问题

    1. 绑定到图片加载事件

    这是最好的解决方案(在撰写本文时),涉及绑定到img.load 事件。您所要做的就是计算有多少个 img 有 $('img').length,然后从该计数中对每个 load-1 进行计数,直到达到零,然后触发均衡器。

    这里需要注意的是,如果图像在缓存中,load 可能不会在所有浏览器中触发。看看google/github,应该有一个解决方案脚本在那里。在撰写本文时,我找到了waitForImages from Alexander Dickson(未经测试,这不是背书)。

    1. 另一个更可靠的解决方案是window.load 事件。这通常应该始终有效。但是,如果您检查docs,您会注意到在加载所有外部资源后会触发此事件。这意味着,如果您的图片已加载,但有一些 javascript 等待下载,则在下载完成之前不会触发。

    如果您异步加载大部分外部组件,并且巧妙地最小化、压缩和分散负载,则此方法可能不会有任何问题,但是突然变慢的 CDN(一直发生)可能会导致问题。

    在这两种情况下,您都可以采用一种愚蠢的方法并应用回退计时器。让均衡脚本在设定的几秒钟后自动运行,以防事件未触发或速度慢到您无法控制的情况。这不是万无一失的,但实际上,如果您正确调整计时器,您将通过此回退满足 99% 的访问者。



    多年后,这仍然得到了支持,现在 flexbox 得到了广泛的支持,您可能只想考虑使用纯 CSS,除非您使用 JS 有特定原因

    .container {
      display: flex;
      border: 2px dashed red;
      margin: 10px 0;
    }
    
    .container > .column { 
     padding: 10px;
    }
    
    .container.fill-width {
      justify-content: stretch;
    }
    
    .container.fill-width>.column {
      flex-grow: 1
    }
    
    .container>.column:nth-child(1) {
      background: yellow;
    }
    
    .container>.column:nth-child(2) {
      background: blue;
    }
    
    .container>.column:nth-child(3) {
      background: green;
    }
    <div class="container">
      <div class="column">Some<br>text</div>
      <div class="column">Some<br>more<br>text<br>here</div>
      <div class="column">One line</div>
    </div>
    <div class="container">
      <div class="column">Some<br>more<br>even<br>longer<br>text<br>here</div>
      <div class="column">Some<br>text</div>
      <div class="column">One line</div>
    </div>
    <div class="container fill-width">
      <div class="column">Some<br>more<br>text<br>here</div>
      <div class="column">Some<br>text</div>
      <div class="column">One line</div>
    </div>

    【讨论】:

    • “更快的答案”,比 9 分钟还快 :)
    • 是的,如果我没有从头开始创建小提琴,它可能更像是 5,但更严重的是,如果 javascript 更复杂,有些人甚至可能不会费心毫不费力地提供帮助,因为他们可能希望“看到它在行动”以解决它。让人们及早养成良好的习惯,我想这对他们有长期的帮助:)
    • @Lee 我学校的互联网由于某种我无法理解的原因阻止了 jsfiddle..
    • 那很奇怪,可能是“小提琴”这个词(如果你不明白为什么我不打算解释)。如果您问他们,他们可能会为您解锁它,因为它是出于教育目的。但是,如果您有兴趣查看我发布的代码,我现在将其放入上面的帖子中
    • @Lee 是我还是我们都发送了完全相同的答案:)
    【解决方案2】:

    这对我有用。尽管有父 div,但它对每列应用相同的高度。

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

    Source

    【讨论】:

      【解决方案3】:

      我希望在我(在 Earl 的帮助下)创建这篇文章之前阅读这篇文章

      setMaxHeightForTitles($column, $title) {
            var maxHeight = 0;
            $column.find($title)
            .each(function(index, title){
              var height = $(title).height();
              if  (height > maxHeight) maxHeight = height;
            })
            .each(function(index, title){
              $(title).height(maxHeight);
            });
        }
      

      【讨论】:

        【解决方案4】:

        你也可以用这种方式编写函数这有助于一次构建你的代码 只是在末尾添加类名或ID

        function equalHeight(group) {
                       tallest = 0;
                       group.each(function() {
                          thisHeight = jQuery(this).height();
                          if(thisHeight > tallest) {
                             tallest = thisHeight;
                          }
                       });
                       group.height(tallest);
                    }
                    equalHeight(jQuery("Add your class"));
        

        【讨论】:

          【解决方案5】:

          因此,在 jquery 脚本下方设置列的相等高度,Math.max 将计算两个 div 的高度并取最高的高度,它可能是左边的也可能是右边的。

          $(document).ready(function() {
          var Equalheights = Math.max($(“#left”).height(), $(“#right”).height());
          $(“#left”). Equalheights(d);
          $(“#right”). Equalheights(d);
          });
          Highest height will be assigned to both left and right divs
          

          Live Demo

          【讨论】:

            【解决方案6】:
            <div class('a')>
               <div class('.cols-to-eq')></div>
               <div class('.cols-to-eq')></div>
               <div class('.cols-to-eq')></div>
               <div class('.cols-to-eq')></div>
            </div>
            <div class('b')>
               <div class('.cols-to-eq')></div>
               <div class('.cols-to-eq')></div>
               <div class('.cols-to-eq')></div>
               <div class('.cols-to-eq')></div>
            </div>
            var a = ['.a','.b'];
            a.forEach(function(value) {
                var column = 0;
                $(value).find('.cols-to-eq').each(function(){
                    if($(this).height() > column){
                        column = $(this).height();
                    }
                });
                $(value).find('.cols-to-
                eq').attr('style','height:'+column+'px');
               });
            

            【讨论】:

              【解决方案7】:
              // Select and loop the container element of the elements you want to equalise
                      $('.equal').each(function(){  
              
                        // Cache the highest
                        var highestBox = 0;
              
                        // Select and loop the elements you want to equalise
                        $('.col-lg-4', this).each(function(){
              
                          // If this box is higher than the cached highest then store it
                          if($(this).height() > highestBox) {
                            highestBox = $(this).height(); 
                          }
              
                        });  
              
                        // Set the height of all those children to whichever was highest 
                        $('.col-lg-4',this).height(highestBox);
              
                      }); 
              
                  });
              

              【讨论】:

                【解决方案8】:
                function setEqualHeight(columns) {
                  var tallestColumn = 0;
                
                  columns.each(function(){
                    var currentHeight = $(this).height();
                
                    if(currentHeight > tallestColumn){
                      tallestColumn  = currentHeight;
                    }
                  });
                
                  columns.height(tallestColumn);
                }
                
                => setEqualHeight($('.column'));
                

                【讨论】:

                  【解决方案9】:

                  有一个用于此目的的 jQuery 插件:https://github.com/dubbs/equal-height

                  如果要使所有列的高度相同,请使用:

                  $('.columns').equalHeight();
                  

                  如果您想按最高位置对它们进行分组,例如。在每个容器内:

                  $('.columns').equalHeight({ groupByTop: true });
                  

                  【讨论】:

                    【解决方案10】:

                    如果容器内部有图像,则需要 imagesLoaded。 这也适用于响应式。

                    $(document).ready(function () { 
                         equalHeight('.column');
                    });
                    $(window).resize(function(){equalHeight('.column');});
                    
                    function equalHeight(columnClass){
                        $('.eq-height-wrap').imagesLoaded(function(){
                            $('.eq-height-wrap').each(function(){  
                    
                                var maxHeight = Math.max.apply(null, $(this).find(columnClass).map(function ()
                                {
                                    return $(this).innerHeight();
                                }).get());
                    
                                $(columnClass,this).height(maxHeight);
                            });
                        });
                    }
                    

                    【讨论】:

                      【解决方案11】:
                        <script>
                      function equalHeight(group) {
                         tallest = 0;
                         group.each(function() {
                            thisHeight = $(this).height();
                            if(thisHeight > tallest) {
                               tallest = thisHeight;
                            }
                         });
                         group.height(tallest);
                      }
                      $(document).ready(function() {
                         equalHeight($(".column"));
                      });
                      </script>
                      

                      【讨论】:

                        【解决方案12】:

                        var currentTallest = 0,
                             currentRowStart = 0,
                             rowDivs = new Array(),
                             $el,
                             topPosition = 0;
                        
                         $('.blocks').each(function() {
                        
                           $el = $(this);
                           topPostion = $el.position().top;
                           
                           if (currentRowStart != topPostion) {
                        
                             // we just came to a new row.  Set all the heights on the completed row
                             for (currentDiv = 0 ; currentDiv < rowDivs.length ; currentDiv++) {
                               rowDivs[currentDiv].height(currentTallest);
                             }
                        
                             // set the variables for the new row
                             rowDivs.length = 0; // empty the array
                             currentRowStart = topPostion;
                             currentTallest = $el.height();
                             rowDivs.push($el);
                        
                           } else {
                        
                             // another div on the current row.  Add it to the list and check if it's taller
                             rowDivs.push($el);
                             currentTallest = (currentTallest < $el.height()) ? ($el.height()) : (currentTallest);
                        
                          }
                           
                          // do the last row
                           for (currentDiv = 0 ; currentDiv < rowDivs.length ; currentDiv++) {
                             rowDivs[currentDiv].height(currentTallest);
                           }
                           
                         });​
                        $('.blocks') would be changed to use whatever CSS selector you need to equalize.

                        【讨论】:

                          【解决方案13】:

                          重要的改进! (我在测量高度之前添加了 $(this).height('auto'); - 我们应该将其重置为自动。然后我们可以在调整大小时使用此功能)

                          function equalheight () {
                                      $('.cont_for_height').each(function(){  
                          
                                          var highestBox = 0;
                                          $('.column_height', this).each(function(){
                          
                                              var htmlString = $( this ).html()
                          
                                              ;
                          
                          
                                          $(this).height('auto');
                          
                                              if($(this).height() > highestBox) 
                                                 highestBox = $(this).height(); 
                                          });  
                          
                                          $('.column_height',this).height(highestBox);
                          
                                  });  
                          
                                  }
                          

                          【讨论】:

                          • 好收获!!对动态内容非常有用。
                          【解决方案14】:

                          这是我在同一高度设置块的版本...例如,您有一个包含名称为“col”的 div 的 div

                          $('.col').parent().each(function() {
                              var height = 0,
                                  column = $(this).find('.col');
                              column.each(function() {
                                  if ($(this).height() > height) height = $(this).height();
                              });
                              column.height(height);
                          });
                          

                          【讨论】:

                            【解决方案15】:

                            你需要这个:

                            $('.container').each(function(){  
                                 var $columns = $('.column',this);
                                 var maxHeight = Math.max.apply(Math, $columns.map(function(){
                                     return $(this).height();
                                 }).get());
                                 $columns.height(maxHeight);
                            });
                            

                            解释

                            • 下面的 sn-p 构造一个高度数组:

                              $columns.map(function(){
                                  return $(this).height();
                              }).get()
                              
                            • Math.max.apply( Math, array ) 查找数组项的最大值

                            • $columns.height(maxHeight); 将所有列的高度设置为最大高度。

                            Live demo

                            【讨论】:

                              【解决方案16】:
                              $(document).ready(function(){
                              
                                  $('.container').each(function(){  
                                      var highestBox = 0;
                              
                                      $(this).find('.column').each(function(){
                                          if($(this).height() > highestBox){  
                                              highestBox = $(this).height();  
                                          }
                                      })
                              
                                      $(this).find('.column').height(highestBox);
                                  });    
                              
                              
                              });
                              

                              【讨论】:

                              • 不错的时机..我正要发布同样的内容:)
                              【解决方案17】:

                              您可以使用.parent() API 访问每个单独的容器。

                              喜欢,

                              var highestBox = 0;
                                      $('.container .column').each(function(){  
                                              if($(this).parent().height() > highestBox){  
                                              highestBox = $(this).height();  
                                      }
                                  }); 
                              

                              【讨论】:

                              • 谢谢,但这不能满足我的需要。所有六个 div 的高度都相同 :(
                              猜你喜欢
                              • 2011-11-04
                              • 1970-01-01
                              • 1970-01-01
                              • 2011-07-29
                              • 2013-01-02
                              • 2010-11-09
                              • 2021-08-10
                              • 1970-01-01
                              • 2021-12-06
                              相关资源
                              最近更新 更多