mha*_*ici 1 javascript jquery grouping wrapall
我想知道如何包装所有相邻且具有相同类的元素。.wrapAll()不起作用,因为它将段落推到了底部。
来源:
<div class="container">
<div class="group"></div>
<div class="group"></div>
<div class="group"></div>
<p>Lorem ipsum dolor sit amet</p>
<div class="group"></div>
<div class="group"></div>
<div class="group"></div>
</div>Run Code Online (Sandbox Code Playgroud)
期望的输出:
<div class="container">
<div class="group-wrapper">
<div class="group"></div>
<div class="group"></div>
<div class="group"></div>
</div>
<p>Lorem ipsum dolor sit amet</p>
<div class="group-wrapper">
<div class="group"></div>
<div class="group"></div>
<div class="group"></div>
</div>
</div>Run Code Online (Sandbox Code Playgroud)
您必须将其分成不匹配元素之间的组。
$(function(){
$.fn.reverse = [].reverse;
var target = '.group', // the class of the elements to group
invert = ':not(' + target + ')', // we create the invert to find the breakpoints
wrap = '<div class="group-wrapper">', // what to wrap with
breakpoints = $('.container > *'+invert); // find the breakpoints in our container
breakpoints.each(function(){
$(this).nextUntil(invert).wrapAll( wrap ); // get the matching elements efter this breakpoint and wrap them
});
breakpoints.first().prevUntil(invert).reverse().wrapAll( wrap ); // wrap the elements before the first breakpoint
});
Run Code Online (Sandbox Code Playgroud)
演示地址:http://jsfiddle.net/gaby/qz53fggd/