jquery - :visible not working with :nth-child selector

标签 jquery css

我有一个网格中的元素列表。其中一些通过 .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
}

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

关于jquery - :visible not working with :nth-child selector,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20557240/

相关文章:

javascript - 为什么我的警报没有显示我希望它显示的 DIV?

jquery - 覆盖 'overflow:hidden' 的父 CSS 规则

jquery - 删除表头时在表单元格中居中输入字段

html - 我的 CSS 中不必要的变量需要影响外观 - 怎么了?

html - 模态流 OUT 问题

css - Google map v3 api 无法在 Bootstrap 中正确呈现(不涉及选项卡)

jquery - Django ajax文件上传表单-文件未上传

javascript - 如何删除特定窗口大小的数据切换 ="modal"?

javascript - HTML 结构不适用于不同的设备

jQuery 验证,同一功能的多个表单 ID