jQuery使另外两个li的高度与最高的相同

时间:2012-12-10 11:09:23

标签: jquery jquery-selectors

我有这个小提琴link。在这里你可以看到我的标记就像ul里面的一堆li。在这里,我将3 lis作为一行,然后将另外3 lis作为另一行,依此类推。现在我已经使用jQuery来获取一个li的高度,其高度比其他2 lis更高,并使2 lis进入与最高li相同的高度。在这里,我的jQuery在第一行工作正常,但它不适用于其他行。那么有人能告诉我如何为其他行执行相同的高度吗?任何帮助和建议都将非常值得一提。 我的jQuery代码就像这样

<script type="text/javascript">
  jQuery(document).ready(function(){
    jQuery(function() {
      var items = $("ul.products li");
      var rows = items.length / 3;
      if (rows <= 0)
        rows = 1;
      for(var r=0;r<rows;r++) {
        normalizeRowHeight(r, items);

      }
    });

    function normalizeRowHeight(row, itemSet) {
      var maxRowHeight = 0;
      itemSet.slice(0,3).each(function(i) {
        if ($(this).height() > maxRowHeight )
          maxRowHeight = $(this).height();
        });  
      itemSet.slice(0,3).each(function(i) {
        $(this).css('height', maxRowHeight + "px");
      });
    }
  });
</script>

3 个答案:

答案 0 :(得分:2)

您需要更新每行.slice()内的数字,以便.slice(0, 3)变为.slice(3, 6),然后变为.slice(6, 9),依此类推。像下面这样的东西可以解决这个问题:

(function($) {
  function normalizeHeight(items) {
    var maxHeight = 0, itemHeight;

    items.each(function() {
      itemHeight = $(this).height();
      if (itemHeight > maxHeight) {
        maxHeight = itemHeight;
      }
    }).height(maxHeight + 'px');
  }

  $(document).ready(function(){
    var itemsPerRow = 3,
        items = $('ul.products li'),
        rows = items.length / itemsPerRow, 
        r, min, max;

    if (rows < 1) rows = 1;

    for(r = 0; r < rows; r++) {
      min = itemsPerRow * r,
      max = min + itemsPerRow;
      normalizeHeight(items.slice(min, max));
    }
  });
}(jQuery));

我放了demo on jsbin

答案 1 :(得分:0)

您的逻辑中有一个洞可以选择您正在操作的切片。你总是处理前3项。

试试这个:

function normalizeRowHeight(row, itemSet) {
  var maxRowHeight = 0;
  itemSet.slice(row * 3,(row + 1)*3).each(function(i) {
    if ($(this).height() > maxRowHeight )
      maxRowHeight = $(this).height();
    });  
  itemSet.slice(row * 3,(row + 1)*3).each(function(i) {
    $(this).css('height', maxRowHeight + "px");
  });
}

答案 2 :(得分:0)

你可以这样做

$(document).ready(function()
        {
            var i=0,j=0;
            $('li').each(function(){
                j=$(this).height();
                if (i<j)
                    i=j;
            });
            $('li').each(function(){
                $(this).height(i);//set Max height of li to other li
                alert($(this).height());
            });
        });

See working Demo

相关问题