:visible not working with:nth-​​child selector [英] :visible not working with :nth-child selector

查看:147
本文介绍了:visible not working with:nth-​​child selector的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a list of items in a grid. Some of them are hidden with CSS using display: none; via a class .hide.

我试图通过添加一个类 .clear-left 来清除每四个可见它。我不明白为什么我的脚本不工作。我使用:可见选择器,但它似乎还在计数项目 display:none;

I'm trying to 'clear' every 4th visible item by adding a class .clear-left to it. I can't understand why my script doesn't work. I'm using the :visible selector but it seems to still be counting items that are display: none;.

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

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


推荐答案

将过滤器更改为检查项目的索引是否可被3整除的函数:

You can't get this with pure CSS, so change your filter to a function that checks to see if the index of the item is divisible by 3:

$itemShow.filter(function(i){ return i % 3 === 0; }).addClass('clear-left');

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

这使用Modulus运算符。

This uses the Modulus operator. It gives you the remainder when dividing two numbers.

0 % 3;  // 0
1 % 3;  // 1
2 % 3;  // 2
3 % 3;  // 0
4 % 3;  // 1
5 % 3;  // 2
6 % 3;  // 0

编辑:但我更喜欢做这种事使用纯CSS限制容器的宽度。

But I prefer to do this sort of thing with pure CSS by limiting the width of the container.

.grid {
  margin-left: -30px;
  width: 606px
}

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

这篇关于:visible not working with:nth-​​child selector的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆