gpt4 book ai didi

html - 选择一个类和其余的前 3 个; nth-child 和 nth-of-type 无用

转载 作者:技术小花猫 更新时间:2023-10-29 12:13:29 31 4
gpt4 key购买 nike

我有一个包含多个子项的 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了解详情。

经过一番修改后,根据您的 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 类一次只会出现在一个元素上。

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

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


就其值(value)而言,如果您可以回退到 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 代码,它只是为了使其具有交互性)

关于html - 选择一个类和其余的前 3 个; nth-child 和 nth-of-type 无用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8631525/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com