6

我正在尝试条纹交替元素的颜色。但我希望行颜色仅交替可见行。如果您查看以下内容,这是我尝试使其正常工作的尝试。

http://jsfiddle.net/kuwFp/3/

<!DOCTYPE html>
<html>
<head>
<style>
p:not(.hide):nth-child(odd)
{
background:#ff0000;
}
p:not(.hide):nth-child(even)
{
background:#0000ff;
}
.hide { display:none; }
</style>
</head>
<body>

<p>The first paragraph.</p>
<p class="hide">The second paragraph.</p>
<p>The third paragraph.</p>

</body>
</html>
4

3 回答 3

5

You can't do this with pure CSS because the :nth-child selector is calculated with respect to the element and :not does not filter element position in the DOM. You need to use JavaScript for a fully flexible solution.

It's still possible for you to do this inflexibly by making elements after .hide with :nth-child alternate the color they should be:

.hide + p:nth-child(odd) {
    background: #0000ff;    
}

You can continue to add similar rules for more and more combinations of sibling .hide and p, but this is very inflexible.

于 2013-02-25T03:07:42.653 回答
1

诀窍是隐藏具有不同标签的行,而不是类。在我的示例中,我使用“del”标签来隐藏。

.list div:nth-of-type(odd) { background: ghostwhite; }
.list del { display: none; }
<div class="list">
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <del>4</del>
  <div>5</div>
  <del>6</del>
  <div>7</div>
</div>

于 2017-02-04T06:06:19.333 回答
0

如果您有权访问隐藏和显示元素的代码,则可以在每个原始隐藏元素之后添加另一个辅助隐藏元素,因此将为 css 选择器保留奇偶性。此外,当原始辅助元素再次出现时,删除每个隐藏的辅助元素。

于 2020-07-15T15:08:52.390 回答