【问题标题】:How to color every second row using jQuery when the number of element in a row is variable?当一行中的元素数量可变时,如何使用jQuery每隔一行着色?
【发布时间】:2011-10-08 05:53:54
【问题描述】:

考虑以下示例,它应该每隔一行着色一次:(live demo here)

JS:

$(function() {
    var wrapper = $("<div></div>")

    for (i = 0; i < 100; i++) {
        wrapper.append("<span></span>");
    }

    $("body").append(wrapper);

    color_rows();
});

function color_rows() {
    $("span").each(function(i) {
        if (i % 10 >= 5) {
            $(this).css("background-color", "red");
        }
    });
}

CSS:

div {
    width: 450px;
    height: 400px;
    background-color: #ccc;
    overflow: auto;
}
span {
    display: inline-block;
    width: 50px;
    height: 50px;
    background-color: #777;
    margin: 0 30px 30px 0;
}

输出是:

如您所见,color_rows() 函数假定每行有 5 个元素。例如,如果我将div 的宽度更改为350pxcolor_rows() 函数将无法正常工作(即不会每隔一行着色)。

如何修复 color_rows() 使其适用于 div 的每个宽度?

【问题讨论】:

  • 不应该 tr:nth-child(odd) 在这里工作吗?编辑:啊!我以为有一张桌子!
  • 不管是不是桌子。 CSS3 nth-child 适用于任何元素,但 Internet Explorer 不支持。

标签: javascript jquery html css


【解决方案1】:

有一个更简单的方法:

$('tr:even').css("background-color", "red");

【讨论】:

    【解决方案2】:

    我已经修复了你的代码,但请不要这样做this。互联网的痛苦,

    $(function() {
        var wrapper = $("<div></div>")
    
        for (i = 0; i < 100; i++) {
            wrapper.append("<span></span>");
        }
    
        $("body").append(wrapper);
    
        color_rows();
    });
    
    function color_rows() {
            var rowWidth = Number( $('div:first').css('width').slice(0,-2) );
            var itemWidth = Number( $('span:first').css('width').slice(0,-2) ) + Number( $('span:first').css('margin-right').slice(0,-2) );
            var perRow =  Math.floor( rowWidth/itemWidth );
    
        $("span").each(function(i) {
            if (i % 10 >= perRow ) {
                $(this).css("background-color", "red");
            }
        });
    }
    

    【讨论】:

      【解决方案3】:

      看看我的修复http://jsfiddle.net/Ug6wD/5/

      我得到容器宽度,itemWidth + margin。并计算每行有多少项目。从 span 项中获取 margin-right。

      然后将容器宽度减去 20,因为溢出滚动条。

      function color_rows() {
      var containerWidth = $('div').width()-20;
      var itemWidth = $('span:first').width() + parseInt($('span:first').css('margin-right'));
      var itemsPerRow = parseInt(containerWidth / itemWidth);
      
      $("span").each(function(i) {
          if (i % (itemsPerRow *2) >= itemsPerRow ) {
              $(this).css("background-color", "red");
          }
      });
      

      } 更新来自 CSS 的动态边距右值和右滚动条修复导致损坏:http://jsfiddle.net/Ug6wD/5/

      【讨论】:

      • 刚刚通过测试得到了相同的解决方案,但它不适用于 div width = 250 或 650,例如...
      • 你应该使用 parseInt(val, 10)
      【解决方案4】:

      这是我的解决方案:

      这基于每个元素的顶部偏移量并通过将其与循环中最后一个元素的顶部偏移量进行比较来检测是否看到新行,然后根据行颜色行数。

      function color_rows() {
          var lastTop = -1;
          var rowCount = 0;
          $("span").each(function(i) {
              var top = $(this).position().top;
              if (top != lastTop) {
                  rowCount++;
                  lastTop = top;
              }
              if(rowCount % 2 == 0)
              {
                  $(this).css("background-color", "red");
              }
          });
      }
      

      jsFiddle:http://jsfiddle.net/Ug6wD/4/

      【讨论】:

      • +1 这也是我的做法——浏览器会知道它何时将元素移动到下一行,所以问问吧!
      • 不错!您可以将$(this).position().top$(this).prev().position().top 进行比较
      • @Salman 每次通过循环时记住它会更有效率 - 您的方式进行 5 次 jQuery 调用,而不是原来的 2 次。
      【解决方案5】:

      小提琴:http://jsfiddle.net/gn5QW/1/

      html

      <div id="container">
          <div class="box"></div>
          <div class="box"></div>
          <div class="box"></div>
          <div class="box"></div>
      </div>
      

      js

      $(document).ready(function(){
          var box = $(".box");
          var con = $("#container");
          var box_per_line = Math.floor(parseInt($("#container").width())/ (parseInt( $(".box").width()) +10*2/*px*/));
          var style = "black";
          $(".box").each(function(i){
              if(i % box_per_line == 0){ style = (style == "black") ? "grey" : "black"; }
              $(this).css("background-color",style);
          });
      });
      

      css

      .box {
          width: 100px;
          height: 100px;
          float: left;
          margin: 10px;
      }
      
      #conainer {
          background-color: grey;
          display: inline-block;
      }
      

      【讨论】:

        【解决方案6】:

        编辑:这仅适用于某些 div 宽度.. -.- 没关系,然后..

        应该这样做:

        function color_rows() {
            var divW = $('div').width();
            var spanW = $('span').outerWidth(true);   //Get margin too
            var cnt = parseInt(divW/spanW, 10);   //Remove decimals
            $("span").each(function(i) {
                if (i % (cnt*2) >= cnt) {
                    $(this).css("background-color", "red");
                }
            });
        }
        

        【讨论】:

        • 这将无法正常工作,因为您忘记了“% 10”。十个值应该是 itemsPerRow * 2,10 仅适用于 itemsPerRow = 5。;) [和边距值]
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-02-03
        • 1970-01-01
        • 2011-07-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-03
        相关资源
        最近更新 更多