Wrap every 3 divs in a div

前端 未结 6 1929
执念已碎
执念已碎 2020-11-22 09:03

Is it possible to use nth-child selectors to wrap 3 divs using .wrapAll? I can\'t seem to work out the correct equation.

so...



        
6条回答
  •  不要未来只要你来
    2020-11-22 09:47

    I've written a generic chunk function that makes this quite easy to do:

    $.fn.chunk = function(size) {
        var arr = [];
        for (var i = 0; i < this.length; i += size) {
            arr.push(this.slice(i, i + size));
        }
        return this.pushStack(arr, "chunk", size);
    }
    
    $("div > div").chunk(3).wrap('
    ');

    $.fn.chunk = function(size) {
      var arr = [];
      for (var i = 0; i < this.length; i += size) {
        arr.push(this.slice(i, i + size));
      }
      return this.pushStack(arr, "chunk", size);
    }
    
    $("div > div").chunk(3).wrap('
    ');
    div > div {
      width: 50px;
      height: 50px;
      background: blue;
      margin: 2px;
      float: left;
    }
    
    div.new {
      background: red;
      height: auto;
      width: auto;
      overflow: auto;
    }
    
    

提交回复
热议问题