简介
CSS3 [attribute$=value] 选择器用于匹配具有指定后缀值的属性的元素。换句话说,它会选择具有属性值以给定值结尾的元素。
语法
[attribute$=value]
其中:
attribute是要匹配的属性名称。value是属性值的后缀。
用法
[attribute$=value] 选择器可以用于各种目的,例如:
- 匹配具有特定文件扩展名的链接:
a[href$=".pdf"] {
color: red;
}- 匹配以特定字符结尾的 ID:
#element[id$="footer"] {
background-color: black;
}- 匹配具有以特定单词结尾的类:
.container[class$="--active"] {
border: 1px solid green;
}示例
以下是一些使用 [attribute$=value] 选择器的示例:
// www.javascriptcn.com code example
/* 匹配具有以 ".png" 结尾的 src 属性的图像 */
img[src$=".png"] {
width: 200px;
height: 200px;
}
/* 匹配具有以 "footer" 结尾的 id 属性的元素 */
#footer[id$="footer"] {
background-color: #f0f0f0;
padding: 20px;
}
/* 匹配具有以 "--active" 结尾的 class 属性的元素 */
.container[class$="--active"] {
color: white;
background-color: #007bff;
}与其他选择器的比较
[attribute$=value] 选择器与其他属性选择器类似,例如 [attribute] 和 [attribute=value]. 然而,它更具体,因为它只匹配具有特定后缀值的属性。
浏览器支持
[attribute$=value] 选择器得到所有主要浏览器的广泛支持,包括 Chrome、Firefox、Safari、Edge 和 Opera。
结论
[attribute$=value] 选择器是一个强大的工具,可用于通过属性值的特定后缀来精确匹配元素。它可以用于各种目的,包括样式化特定文件类型、元素 ID 和类。