选择奇数偶数孩子,不包括隐藏的孩子

car*_*mba 24 css css-selectors css3

第2行和第3行之间是隐藏的<div>.我不希望从odd/even css规则中取出那个.什么是使这个工作的最佳方法?http://jsfiddle.net/k0wzoweh/

在此输入图像描述

<style>
.box:not(.hidden):nth-child(even) {background: green}
.box:not(.hidden):nth-child(odd) {background: orange}
.hidden {display:none;}
</style>
<div class="wrap">
    <div class="box">xx</div>
    <div class="box">xx</div>
    <div class="box hidden">xx</div>
    <div class="box">xx</div>
    <div class="box">xx</div>
    <div class="box">xx</div>
    <div class="box">xx</div>
</div>
Run Code Online (Sandbox Code Playgroud)

注意:可以有多个hidden元素.

Has*_*ami 38

:nth-child()伪类看起来通过父的孩子树相匹配的有效子(odd,even,等),因此,当你把它与:not(.hidden)它不会正确地过滤的元素.

或者,我们可以通过CSS渐变伪造效果,如下所示:

.hidden {display:none;}

.wrap {
  line-height: 1.2em;
  
  background-color: orange; 
  background-image: linear-gradient(transparent 50%, green 50%);
  background-size: 100% 2.4em;
}
Run Code Online (Sandbox Code Playgroud)
<div class="wrap">
  <div class="box">xx</div>
  <div class="box">xx</div>
  <div class="box hidden">xx</div>
  <div class="box">xx</div>
  <div class="box">xx</div>
  <div class="box">xx</div>
  <div class="box">xx</div>
</div>
Run Code Online (Sandbox Code Playgroud)

  • this is to crazy it deserves +1 (7认同)
  • Although it might not be the best solution, I like your style(sheet). +1 (2认同)

Joe*_*Joe 13

伪选择器不会叠加,因此您:not不会影响:nth-child(也不会影响:nth-of-type等)

如果您可以使用jQuery,那么您可以在:visible那里使用伪选择器,尽管这不是CSS规范的一部分.

如果您正在生成HTML并且可以更改它,则可以在运行时应用奇数/偶数逻辑,例如在PHP中:

foreach ($divs AS $i => $div) {
    echo '<div class="box ' . ($i % 2 ? 'even' : 'odd') . '">x</div>';
}
Run Code Online (Sandbox Code Playgroud)

甚至试图做一些棘手的事情

.box[class='box']:nth-of-type(even)
Run Code Online (Sandbox Code Playgroud)

不起作用,因为伪选择器甚至没有堆叠到属性选择器上.

我不确定是否有任何方法可以用CSS完全做到这一点 - 我现在想不出来.


小智 9

这是一个仅使用 CSS 的解决方案:

.box {
  background: orange;
}

.box:nth-child(even) {
  background: green;
}

.box.hidden {
  display: none;
}

.box.hidden ~ .box:nth-child(odd) {
  background: green;
}

.box.hidden ~ .box:nth-child(even) {
  background: orange;
}
Run Code Online (Sandbox Code Playgroud)
<div class="wrap">
  <div class="box">xx</div>
  <div class="box">xx</div>
  <div class="box hidden">xx</div>
  <div class="box">xx</div>
  <div class="box">xx</div>
  <div class="box">xx</div>
  <div class="box">xx</div>
</div>
Run Code Online (Sandbox Code Playgroud)

  • 如果两个隐藏元素一个接一个,则不起作用:https://jsfiddle.net/nuxcskx5/ 或者如果有多个“隐藏”元素:https://jsfiddle.net/nuxcskx5/1/ (4认同)

小智 8

尝试选择器

.hidden {display:none;}
.box:nth-child(odd of :not(.hidden))  { background: orange; }
.box:nth-child(even of :not(.hidden)) { background: green; }
Run Code Online (Sandbox Code Playgroud)


Fat*_*lsa 6

由于我的行被js隐藏,我发现对我来说最简单的方法是在我隐藏的每个实际行之后添加一个额外的隐藏行,并在我再次显示实际行时删除隐藏的行.