【发布时间】:2012-01-27 17:26:25
【问题描述】:
我有一个带有多个子元素的 DOM 元素 (#installations),其中只有一个具有 .selected 类。我需要选择这个类和其余的前 3 个(:not(.selected))并显示它们 - 目标是只显示 4 个元素,无论哪个元素具有 .selected 类。
问题在于,在表达式中:
#installations > *:not(.selected):nth-of-type(-n+3), .selected
:nth-of-type() 忽略 :not() 选择器,只选择#installation 的前 3 个子项。例如,如果我有这个 HTML:
<div id="installations">
<div id="one"/>
<div id="two"/>
<div id="three" class="selected"/>
<div id="four"/>
<div id="five"/>
</div>
我只会选择一个、两个、三个而不是前四个。逻辑含义是 :nth-of-type() 将只有 (一、二、四、五) 可供选择,因为 :not() 已经排除了选定的一个,因此选择了 (一、二、四),然后选择器, .selected 的另一部分将添加所选元素。
如果 .selected 不在前四个元素中,假设它是第六个,我们将选择前三个 + 第六个元素。
澄清一下:选择 .selected 加上 3 个相邻元素也可以。但是,如果 .selected 在最后 3 个中(如果我们选择接下来的 3 个相邻元素),这也很困难
【问题讨论】:
-
伪类不按顺序处理;他们都在你的每一个元素上一起评估。有关详细信息,请参阅 this answer(也包括
:not())。在您的情况下,:not(.selected):nth-of-type(-n+3)选择前两个元素(第三个是.selected),.selected选择第三个。 -
这就是问题所在。如果我能在选择器的第一部分(在第一个伪类之前)排除 .selected 就好了。或者,我可以在所有其他元素上放置一个“.unselected”类,但我希望有一个更清洁的解决方案。
标签: html css css-selectors