:可见无法使用:nth-​​child选择器

我有一个网格中的项目列表。 其中一些使用display: none;使用CSS隐藏display: none; 通过class级.hide

我试图通过添加一个类.clear-left来“清除”每个第四个可见项目。 我无法理解为什么我的脚本不起作用。 我正在使用:visible选择器,但似乎仍在计算display: none;

应该发生的是,你应该总是看到一行中有3个项目没有间隙。

http://jsbin.com/ipORemIs/1/edit

HTML

 
1
2
3
4
5
6

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来获得它,所以将你的filter更改为一个函数,检查项目的索引是否可以被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 } 

http://jsbin.com/oXeGeGus/2/edit

nth-child选择器不能基于自定义索引工作……它基于基于兄弟元素的索引工作,所以你必须自己实现过滤

 var $itemShow = $('.item:visible'); $itemShow.filter(function(idx){ return idx % 4 == 3;//because index starts with 0 }).addClass('clear-left'); 

演示: 小提琴

nth-child仅适用于节点名称,不适用于任何其他类或伪类或任何其他已应用的类。

您将不得不遍历所有可见项目,并仅在i%4==3应用您的类。

这就是我在我的代码中实现它的方式,我需要在类“cities”的每5个可见div之后显示一个div:

 var $itemShow = $('.cities:visible'); $itemShow.filter(function(i){ return (i+1) % 5 == 0; }).after(function(){return "
Reminded that I needed to put after every 5 divs of the class 'cities' or after the last 'cities' div if the total of divs of the class 'cities' is less than 5.
";});

i+1因为第一个元素的索引为零。

在我的情况下,如果class级“城市”的div数小于5,我也想显示提醒,所以我也添加了这个代码:

 if($('.cities:visible').length < 5){ $('.cities:visible').last().after("
Reminded that I needed to put after every 5 divs of the class 'cities' or after the last 'cities' div if the total of divs of the class 'cities' is less than 5.
"); }