0

我有一组这样的元素:

<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" />');

但它只是围绕着整个地段。它真的必须从零索引开始,然后下一个,直到它到达一个 .box.fs 然后环绕在那之前的所有东西。我不确定如何将其传达给代码。也许别人知道?

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

4

3 回答 3

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();
}
于 2013-05-30T14:17:39.130 回答
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 依赖的情况下处理列。

于 2013-05-30T14:15:05.713 回答
0

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

于 2013-05-30T13:34:03.953 回答