我有一个网格中的元素列表。其中一些通过 .hide
类使用 display: none;
通过 CSS 隐藏。
我试图通过向其添加类 .clear-left
来“清除”每第 4 个visible 元素。我不明白为什么我的脚本不起作用。我正在使用 :visible 选择器,但它似乎仍在计算 display: none;
的元素。
应该发生的是,您应该始终看到 3 个元素连续排列且没有间隙。
http://jsbin.com/ipORemIs/1/edit
HTML
<div class="grid">
<div class="item">
1
</div>
<div class="item hide">
2
</div>
<div class="item">
3
</div>
<div class="item">
4
</div>
<div class="item hide">
5
</div>
<div class="item">
6
</div>
</div>
CSS
body {
margin: 0;
}
.grid {
margin-left: -30px;
}
/* Items that are hidden */
.hide {
display: none;
}
.item {
width: 150px;
float: left;
border: 1px solid;
margin-left: 30px;
margin-bottom: 30px;
padding: 10px;
font-size: 3em;
text-align: center;
}
.clear-left {
clear: left;
}
JS
var $itemShow = $('.item:visible');
$itemShow.filter(':nth-child(3n+1)').addClass('clear-left');
最佳答案
你不能用纯 CSS 得到这个,所以把你的过滤器改成一个函数来检查元素的索引是否能被 3 整除:
$itemShow.filter(function(i){ return i % 3 === 0; }).addClass('clear-left');
http://jsbin.com/OVewUkaM/1/edit
这使用模运算符。它会为您提供两个数字相除时的余数。
0 % 3; // 0
1 % 3; // 1
2 % 3; // 2
3 % 3; // 0
4 % 3; // 1
5 % 3; // 2
6 % 3; // 0
编辑:但我更喜欢通过限制容器的宽度来使用纯 CSS 来做这种事情。
.grid {
margin-left: -30px;
width: 606px
}
关于jquery - :visible not working with :nth-child selector,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20557240/