使用jQuery为div设置相同的高度

时间:2012-07-27 12:58:57

标签: jquery html height equals

我想用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才能达到这个目标?

谢谢!

15 个答案:

答案 0 :(得分:81)

回答您的具体问题

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

  • 遍历每个容器
    • 获取该容器中每列的高度
    • 找到最高的
    • 将该高度应用于该容器中的每一列,然后再转到下一列。
  

注意:尝试提供您的问题的示例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. 绑定图像加载事件
  2. 这是最好的解决方案(在撰写本文时)并涉及绑定到img.load事件。您所要做的就是计算$('img').length有多少img,然后从该计数中计算每个load-1,直到您达到零,然后触发均衡器。

    如果图像位于缓存中,则此处的警告load可能无法在所有浏览器中触发。环顾谷歌/ github,应该有一个解决方案脚本。在撰写本文时,我发现waitForImages from Alexander Dickson(未经测试,这不是认可)。

    1. 另一个更可靠的解决方案是window.load事件。这应该总是有效。但是,如果您检查docs,则会注意到在加载所有外部资源后会触发此事件。这意味着如果你的图像被加载但是有一些javascript等待下载它将不会触发,直到完成。
    2. 如果您异步加载大部分外部设备并且在最小化,压缩和传播负载方面很聪明,那么这种方法可能不会出现任何问题,但突然发生的CDN(一直发生)可能会导致问题。

      在这两种情况下,您都可以采取愚蠢的方法并应用后备计时器。让equize脚本在设置几秒后自动运行,以防万一事件没有触发或者某些事情发生在您的控制之外。这不是万无一失的,但实际上,如果你正确地调整计时器,你可以通过这个后备来满足99%的访问者。

答案 1 :(得分:9)

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


});

答案 2 :(得分:4)

重要改进! (我添加了$(this).height('auto');在测量高度之前 - 我们应该将它重置为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);

        });  

        }

答案 3 :(得分:3)

这是我在同一个hight中设置块的版本...例如,你有一个包含名为“col”的div的divt

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

答案 4 :(得分:1)

您也可以通过这种方式编写函数,这有助于一次构建代码 只是在最后添加类名或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 :(得分:1)

&#13;
&#13;
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);
   }
   
 });​
&#13;
$('.blocks') would be changed to use whatever CSS selector you need to equalize.
&#13;
&#13;
&#13;

答案 6 :(得分:1)

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

答案 7 :(得分:1)

因此,在jquery脚本下面,将等于高度的列设置为Math.max将计算两个divs高度并采用最高高度的列,该高度可以是左侧或右侧。

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

答案 8 :(得分:1)

希望(在伯爵的帮助下)创建这篇文章之前,我会读完这篇文章

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

答案 9 :(得分:0)

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

像,

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

答案 10 :(得分:0)

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

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

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

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

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

答案 11 :(得分:0)

ext-jars

答案 12 :(得分:0)

lines()

答案 13 :(得分:0)

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

答案 14 :(得分:0)

这对我有用。尽管它们的父级为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

相关问题