在组中包装元素

时间:2013-05-30 13:28:10

标签: jquery html

我有一组这样的元素:

<div class="cols">
 <div class="col">
  <div class="box"></div>
  <div class="box"></div>
  <div class="box fs"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box fs"></div>
  <div class="box"></div>
 </div>
</div>

我想将这样的元素分组:

 <div class="col">
  <div class="g">
   <div class="box"></div>
   <div class="box"></div>
  </div>
  <div class="g">
   <div class="box fs"></div>
  </div>
  <div class="g">
   <div class="box"></div>
   <div class="box"></div>
  </div>
  <div class="g">
   <div class="box fs"></div>
  </div>
  <div class="g">
   <div class="box"></div>
  </div>
 </div>
</div>

我正在尝试按照

的方式行事
$('div.cols div.col div.box').nextUntil('.box.fs').andSelf().wrapAll('<div class="g" />');

但它只是围绕着整个地段。它真的必须从零索引开始然后nextuntil它击中.box.fs然后在此之前包装所有内容。我不确定如何将其传达给代码。也许其他人都知道?

原因:我正在尝试为桌面设备和移动设备上使用的样式表创建多/单列布局。

3 个答案:

答案 0 :(得分:2)

var start = 0;
var boxes = $(".cols .col .box");
while(start < boxes.size()) {
  var box = boxes.eq(start);
  var group =  box.hasClass('fs') ? box : box.nextUntil(".fs").andSelf();
  group.wrapAll("<div class='g'>");
  start += group.size();
}

答案 1 :(得分:1)

公平警告:对于一个丑陋的问题(没有冒犯),这是一个丑陋的答案。

这是一个小提琴:http://jsfiddle.net/crowjonah/P5ydr/和一些代码:

// first, grap all the .fs boxes
$('.fs').wrap('<div class="g" />');

var group = [];
$('.col > .box').each(function() {
    group.push($(this));
    if (!$(this).next().hasClass('box')) {

        // next one doesnt have box class, so wrap group
        var target = $('<div class="g" />');
        $(group).each(function(){

            // add each grouped box to a g container
            $(this).clone().appendTo($(target));
        });

        // insert g container before the first box from the group its replacing
        $(target).insertBefore($(group)[0]);

        $(group).each(function(){
            // remove each original box from the group
            $(this).remove();
        });

        // make way for a new group of boxes
        group = [];
    }
});

如果可能的话,我会重新考虑你的情况,看看是否有更好的方法来构建你的内容并调整标记,以便纯css可以处理列而没有这种可怕的javascript依赖。

答案 2 :(得分:0)

尝试使用简单的.append和.prepend在前面和末尾添加外部框html代码,然后将每个box.fs div放在prepend之前。