如何选择具有两个类之一但不能同时具有两个类的元素?
我试过了 :not(.class1, .class2)
和 :not(.class1):not(.class2)
但他们似乎选择了缺少任何一个类的元素。我需要选择没有两个类的元素。
我也试过:not([class='class1 class2'])
as this accepted answer states , 但它似乎没有选择任何东西。
这是我想要的示例 -
ul.tabs > li.active:not([class='first last']) {
background-color: #F00;
}
<ul class="tabs">
<li class="first">1st</li>
<li class="active last">2nd</li> <!-- Should be red -->
</ul>
<ul class="tabs">
<li class="active first last">1st</li> <!-- Should NOT be red -->
</ul>
<li>
还有其他我不负责的类(class)。我想知道是否有办法忽略我最后尝试的选择器的其他类。
最佳答案
你想要 :not(.first), :not(.last)
这是 :not(.first.last)
的选择器级别 3 支持的版本(来自 Selectors 4,尚未被所有浏览器以及 jQuery 支持):
ul.tabs > li.active:not(.first), ul.tabs > li.active:not(.last) {
background-color: #F00;
}
<ul class="tabs">
<li class="first">1st</li>
<li class="active last">2nd</li>
</ul>
<ul class="tabs">
<li class="active first last">1st</li>
</ul>
不过,正如 Rounin 指出的那样,您应该能够只使用 :first-of-type
和 :last-of-type
,或者 : first-child
和 :last-child
,而不是用“first”和“last”类来膨胀标记(如果这些类表示与伪类相同的东西)。
事实上,如果你切换到那些伪类,你可以通过压缩 :not(:first-of-type), :not(:last-of-type 将你的 CSS 简化为只有一个选择器)
到 :not(:only-of-type)
:
ul.tabs > li.active:not(:only-of-type) {
background-color: #F00;
}
<ul class="tabs">
<li>1st</li>
<li class="active">2nd</li>
</ul>
<ul class="tabs">
<li class="active">1st</li>
</ul>
关于css - 具有两个类之一但不能同时具有两个类的元素的选择器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50289786/