正如我的评论中所提到的,伪类没有被顺序处理;它们都是对每一个元素进行评估的.详见
this answer.
经过一点修补,给出你的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)
为了使其工作,必须做一个简单的假设:所选类只能一次出现在一个元素上.
您需要在同一条规则中组合所有三个选择器,才能匹配您要查找的四个元素.注意我的代码中的逗号.
对于什么是值得的,如果你可以回到JavaScript,这更容易.举个例子,如果你使用jQuery,它的:lt() selector使事情变得更简单一些:
// Apply styles using this selector instead: #installations > div.with-jquery
$('#installations')
.children('div.selected, div:not(.selected):lt(3)')
.addClass('with-jquery');