我有一个包含两列的主列表。在这些列中,每个div都有多个类,当您选择其中一个类时,我想对列进行排序,使它们均匀。这是我开始的一个例子:
<div class="left">
<div class="dot blue">blue one</div>
<div class="dot red">red one</div>
<div class="dot orange">orange one</div>
<div class="dot red">red two</div>
<div class="dot red">red three</div>
</div>
<div class="right">
<div class="dot red">red four</div>
<div class="dot blue">blue two</div>
<div class="dot blue">blue three</div>
<div class="dot blue">blue four</div>
<div class="dot orange">orange two</div>
</div>
点击我的“红色”切换按钮后,我想隐藏除红点之外的所有内容,但是在两列之间均匀地对红色点进行排序。我可以正确隐藏所有内容,但不确定如何在“左”和“右”div之间制作四个红色div。这是我想要的输出:
<div class="left">
<div class="dot red">red one</div>
<div class="dot red">red two</div>
</div>
<div class="right">
<div class="dot red">red three</div>
<div class="dot red">red four</div>
</div>
提前致谢。
答案 0 :(得分:0)
将所有.red
移到左侧,然后找到中途点并将组的后半部分移回右侧:
$('.left,.right').find('.dot:not(.red)').hide(); /* or .remove() */
var $red = $('.left,.right').find('.dot.red').appendTo('.left');
var len = Math.round($red.length/2);
$('.left .dot.red:gt('+(len-1)+')').appendTo('.right'); /* :gt is zero-based */
答案 1 :(得分:0)
您可以使用
$(function(){
var dots = $('.dot'),
left = $('.left'),
right = $('.right');
$('button').on('click', function(){
var filter = $(this).data('filter'); // here you define which class to remain (on demo i have added a data-filter attribute on the buttons)
var filtered = dots.detach().filter('.' + filter),
half = Math.ceil(filtered.length / 2);
filtered.each(function(index){
var target = left;
if (index >= half){
target = right;
}
$(this).appendTo( target );
});
});
});
答案 2 :(得分:0)
我知道你有一些选择,但我在这方面工作了一点,并认为我也会分享我的:
这是我的jQuery:
$(document).ready(function () {
$("button").click(function () {
var classVal = "." + $(this).val();
$(".dot").hide();
$(classVal).show();
var halfOf = ($(classVal).length / 2)-1;
$(classVal).appendTo(".left");
$(classVal+":gt('"+halfOf+"')").appendTo(".right");
});
});
以下是HTML,但我必须添加你所谈到的按钮:
<div class="left">
<div class="dot blue">blue one</div>
<div class="dot red">red one</div>
<div class="dot orange">orange one</div>
<div class="dot red">red two</div>
<div class="dot red">red three</div>
</div>
<div class="right">
<div class="dot red">red four</div>
<div class="dot blue">blue two</div>
<div class="dot blue">blue three</div>
<div class="dot blue">blue four</div>
<div class="dot orange">orange two</div>
</div>
<div id="controls">
<button value="red" type="button">Red</button>
<button value="blue" type="button">Blue</button>
<button value="orange" type="button">Orange</button>
</div>
然后是一些简单的CSS:
.left {
float: left;
border: 1px solid #000000;
}
.right {
float: left;
border: 1px solid #000000;
}
#controls {
clear: both;
}
随着小提琴: