通过CSS属性选择器确定属性是否不存在?

3

你能否使用CSS属性选择器或选择器组合来确定属性是否不存在

可以使用属性选择器来测试属性是否为空:

[aria-label='']

...但是这个属性仍然必须存在,才能通过测试。如果HTML标签根本没有该属性,则上述选择器无法通过测试。

是否可以编写一个选择器,以使其在属性不存在时也能通过测试?


1
规范:属性存在和值选择器 - Oriol
3个回答

2

是的,使用:not()伪类非常简单:

span:not([wrong]) {
  color: blue
}
<span>I have no attribute</span><br/>
<span wrong>I have the wrong attribute :-(</span>


谢谢!3位快速回答的人表明我在选择器中不需要使用“=”。 - Nicholas Pappas

2
您可以应用属性选择器和:not()否定伪类的组合:

您可以使用属性选择器和:not()否定伪类的组合:

div[orange] { background-color: orange; }                       /* 1 */

div:not([orange]) { background-color: lightgreen; }             /* 2 */

div { height: 50px; }
<div>Does not have the orange attribute</div>
<div orange>Has the orange attribute</div>
<div green>Does not have the orange attribute</div>
<div orange="orange">Has the orange attribute</div>

注意:

  1. 选择有 orange 属性的 div 元素。
  2. 选择没有 orange 属性的 div 元素。

参考资料:


1
谢谢!我之前没有意识到可以在不使用比较运算符的情况下使用该属性。 - Nicholas Pappas

1
像这样的内容?

div:not([aria-label]) {
  color: red;  
}
<div aria-label="test">
  test
</div>

<div>
  test2
</div>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接