我有一个带有许多子元素的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()将只有(1,2,4,5)可供选择,因为: to ()已经排除了所选的元素,因此选择了(1,2,4),然后选择器, .selected
的另一部分将添加所选的元素。
如果.selected不在前四个元素中,假设它是第六个元素,那么我们将选择前三个+第六个元素。
澄清:选择.selected +3个相邻元素也很好。但是,如果.selected在最后3个(如果我们选择接下来的3个相邻元素),这也是很困难的。
发布于 2011-12-25 21:34:18
正如我在注释中提到的,伪类不是按顺序处理的;它们都是在每个元素上一起评估的。详情请参见这个答案。
考虑到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)
为此,必须做一个简单的假设:selected
类一次只能出现在一个元素上。
您需要将所有三个选择器合并在同一条规则中,以便匹配您要寻找的四个元素。注意我的代码中的逗号。
交互式jsFiddle演示 (用于测试具有不同子元素中的类的选择器)
不管它的价值是什么,如果你可以回到JavaScript,就更容易了。例如,如果使用jQuery,它的选择器使事情变得更简单:
// Apply styles using this selector instead: #installations > div.with-jquery
$('#installations')
.children('div.selected, div:not(.selected):lt(3)')
.addClass('with-jquery');
交互式jsFiddle演示 (忽略本演示中的JS代码,它只是为了使其具有交互性)
发布于 2011-12-25 21:12:00
您需要使用的是相邻的同胞选择器。下面是一个在Safari中工作的示例(没有在其他地方进行测试)。只显示“二”、“三”和“四”项。
<!DOCTYPE html>
<html>
<head>
<style>
.the-list li {display:none;}
.the-list li.selected {display:block;}
.the-list li.selected + li {display:block;}
.the-list li.selected + li + li {display:block;}
</style>
</head>
<body>
<ol class='the-list'>
<li>One</li>
<li class='selected'>Two</li>
<li>Three</li>
<li>Four</li>
<li>Five</li>
<li>Six</li>
</ol>
</body>
</html>
https://stackoverflow.com/questions/8631525
复制相似问题