选择一个班级,其余3个; nth-child和nth-of-type无用

Ivo*_*Ivo 16 html css css-selectors css3

我有一个带有多个子元素的DOM元素(#installations),其中只有一个有一个类.selected.我需要选择这个类和其余的前三个(:not(.selected))并显示它们 - 目标是只显示4个元素,无论哪个元素具有类.selected.

问题是,在表达式中:

#installations > *:not(.selected):nth-of-type(-n+3), .selected
Run Code Online (Sandbox Code Playgroud)

: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>
Run Code Online (Sandbox Code Playgroud)

我只会选择一个,两个,三个而不是前四个.逻辑含义是:nth-​​of-type()只有(一,二,四,五)可供选择,因为:not()已经排除了所选的一个,因此选择(一,二,四),然后选择器的另一部分, .selected将添加所选元素.

如果.selected不在前四个元素中,让我们说它是第六个,我们将选择前三个+第六个元素.

澄清一下:选择.selected加上3个相邻元素也没关系.但是,我这也很困难.选中的是最后3个(如果我们选择接下来的3个相邻元素)

Bol*_*ock 36

正如我的评论中提到的,伪类不是按顺序处理的; 它们全部在每个元素上进行评估.有关详情,请参阅此答案.

经过一些修修补补,鉴于你的HTML和选择元素的条件,我想出了以下很长的选择器列表:

/* The first three children will always be selected at minimum */
#installations > div:nth-child(-n+3),
/* Select .selected if it's not among the first three children */
#installations > div.selected,
/* If .selected is among the first three children, select the fourth */
#installations > div.selected:nth-child(-n+3) ~ div:nth-child(4)
Run Code Online (Sandbox Code Playgroud)

为了实现这一点,必须做出一个简单的假设:selected类一次只出现在一个元素上.

您需要在同一规则中组合所有三个选择器,以匹配您正在寻找的四个元素.注意我的代码中的逗号.

交互式jsFiddle演示(用于测试选择器与不同子元素中的类)


对于它的价值,如果你可以回归JavaScript,那就更容易了.作为一个例子,如果你使用jQuery,它的:lt()选择器使事情变得更简单:

// Apply styles using this selector instead: #installations > div.with-jquery
$('#installations')
    .children('div.selected, div:not(.selected):lt(3)')
    .addClass('with-jquery');
Run Code Online (Sandbox Code Playgroud)

交互式jsFiddle演示(忽略此演示中的JS代码,它只在那里使其交互)