微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

html – 选择一个类,其余的第3个;第n个孩子和第n个类型没用

我有一个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-​​type()将只有(1,2,4,5)才能选择,因为:not()已经排除了所选择的一个,因此选择(一,二,四)然后选择器的另一部分.selected将添加所选元素.

如果选择的不是前四个要素,那就说这是第六个,我们将选出前三个第六个元素.

澄清:选择.selected加3个相邻元素也很好.但是,我也很困难,如果选择在最后3个(如果我们选择接下来的3个相邻元素)

解决方法

正如我的评论中所提到的,伪类没有被顺序处理;它们都是对每一个元素进行评估的.详见 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)

为了使其工作,必须做一个简单的假设:所选类只能一次出现在一个元素上.

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

Interactive jsFiddle demo(用于测试不同子元素中的类的选择器)

对于什么是值得的,如果你可以回到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');

Interactive jsFiddle demo(忽略这个演示中的JS代码,只是让它进行交互)

原文地址:https://www.jb51.cc/html/231338.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐