简介
[attribute] 选择器允许您根据元素的属性来选择元素。该选择器具有以下语法:
[attribute]
其中 attribute
可以是元素的任何有效属性。
基本用法
要选择具有特定属性的元素,您只需使用属性名称即可。例如,要选择具有 id
属性的元素,您可以使用以下选择器:
[id]
这将选择所有具有 id
属性的元素,无论其值是什么。
特定值选择
要选择具有特定属性值元素,您可以在属性名称后使用 =
操作符,然后指定值。例如,要选择具有 id
属性值为 "my-element" 的元素,您可以使用以下选择器:
[id="my-element"]
值包含选择
要选择属性值包含特定字符串的元素,您可以在属性名称后使用 ~=
操作符,然后指定值。例如,要选择属性值包含 "example" 的元素,您可以使用以下选择器:
[attribute~="example"]
值开头选择
要选择属性值以特定字符串开头的元素,您可以在属性名称后使用 ^=
操作符,然后指定值。例如,要选择属性值以 "example" 开头的元素,您可以使用以下选择器:
[attribute^="example"]
值结尾选择
要选择属性值以特定字符串结尾的元素,您可以在属性名称后使用 $=
操作符,然后指定值。例如,要选择属性值以 "example" 结尾的元素,您可以使用以下选择器:
[attribute$="example"]
布尔属性
对于布尔属性,您无需指定值。例如,要选择具有 disabled
属性的元素,您可以使用以下选择器:
[disabled]
否定选择
要选择不具有特定属性的元素,您可以在属性名称前使用 :
伪类和 not()
函数。例如,要选择不具有 id
属性的元素,您可以使用以下选择器:
:not([id])
示例
以下是一些使用 [attribute] 选择器的示例:
- 选择具有
class
属性值为 "my-class" 的所有元素:
[class="my-class"]
- 选择具有
data-role
属性值为 "button" 的所有元素:
[data-role="button"]
- 选择具有
href
属性值包含 "example" 的所有链接:
[href~="example"]
- 选择属性值以 "example" 开头的所有元素:
[attribute^="example"]
- 选择属性值以 "example" 结尾的所有元素:
[attribute$="example"]
- 选择不具有
disabled
属性的所有元素:
:not([disabled])
浏览器支持
[attribute] 选择器在所有现代浏览器中都得到很好的支持。