如果你希望它只是 CSS,禁用逻辑应该由 CSS 定义。
要移动 CSS 定义中的逻辑,您必须使用属性选择器。以下是一些示例:
禁用具有精确href的链接:=
您可以选择禁用包含特定 href 值的链接,如下所示:
<a href="//website.com/exact/path">Exact path</a>
[href="//website.com/exact/path"]{
pointer-events: none;
}
禁用包含一段路径的链接:*=
在这里,任何包含/keyword/in 路径的链接都将被禁用:
<a href="//website.com/keyword/in/path">Contains in path</a>
[href*="/keyword/"]{
pointer-events: none;
}
禁用以下开头的链接:^=
[attribute^=value] 运算符针对以特定值开头的属性。它允许您丢弃网站和根路径。
<a href="//website.com/begins/with/path">Begins with path</a>
[href^="//website.com/begins/with"]{
pointer-events: none;
}
您甚至可以使用它来禁用非 https 链接。例如:
a:not([href^="https://"]){
pointer-events: none;
}
禁用以下结尾的链接:$=
[attribute$=value] 运算符针对以特定值结尾的属性。丢弃文件扩展名可能很有用。
<a href="/path/to/file.pdf">Link to pdf</a>
[href$=".pdf"]{
pointer-events: none;
}
或任何其他属性
CSS 可以针对任何 HTML 属性。可能是rel、target、data-custom等等……
<a href="#" target="_blank">Blank link</a>
[target=_blank]{
pointer-events: none;
}
组合属性选择器
您可以链接多个规则。假设您要禁用每个外部链接,但不是那些指向您网站的链接:
a[href*="//"]:not([href*="my-website.com"]) {
pointer-events: none;
}
或禁用指向特定网站 pdf 文件的链接:
<a href="//website.com/path/to/file.jpg">Link to image</a>
[href^="//website.com"][href$=".jpg"] {
color: red;
}
浏览器支持
从 Internet Explorer 7 开始支持属性选择器。从 Internet Explorer 9 开始支持 :not() 选择器。