带正则表达式的CSS2属性选择器
时间:2020-03-05 18:49:14 来源:igfitidea点击:
CSS属性选择器允许根据属性值选择元素。不幸的是,我已经好几年没有使用它们了(主要是因为并非所有现代浏览器都支持它们)。但是,我清楚地记得,通过使用类似于以下内容的代码,我能够使用它们来装饰带有图标的所有外部链接:
a[href=http] { background: url(external-uri); padding-left: 12px; }
上面的代码不起作用。我的问题是:它如何运作?如何选择其href属性以" http"开头的所有<a>标签?官方的CSS规范(上面有链接)甚至没有提到这是可能的。但是我确实记得这样做。
(注意:明显的解决方案是使用class
属性进行区分。我想避免这种情况,因为对HTML代码的构建方式影响很小。我只能编辑CSS代码。)
解决方案
回答
至于CSS 2.1,请参见http://www.w3.org/TR/CSS21/selector.html#attribute-selectors
执行摘要:
Attribute selectors may match in four ways: [att] Match when the element sets the "att" attribute, whatever the value of the attribute. [att=val] Match when the element's "att" attribute value is exactly "val". [att~=val] Match when the element's "att" attribute value is a space-separated list of "words", one of which is exactly "val". If this selector is used, the words in the value must not contain spaces (since they are separated by spaces). [att|=val] Match when the element's "att" attribute value is a hyphen-separated list of "words", beginning with "val". The match always starts at the beginning of the attribute value. This is primarily intended to allow language subcode matches (e.g., the "lang" attribute in HTML) as described in RFC 3066 ([RFC3066]).
CSS3还定义了一个选择器列表,但是兼容性差异很大。
还有一个漂亮的测试套件,可以显示哪些选择器在浏览器中起作用。
至于你的例子
a[href^=http] { background: url(external-uri); padding-left: 12px; }
应该做到的。不幸的是,IE不支持它。
回答
请注意,在Antti的示例中,我们可能希望为我们可能拥有的指向我们自己的域的绝对链接添加一个捕获,我们可能不想将其标记为``外部'',例如
a[href^="http://your.domain.com"] { background: none; padding: 0; }
并且我们希望在上一次声明之后执行此操作。
我们可能还希望包括完整的协议前缀,以防万一我们有一个本地文档" http-info.html"想要链接到,例如:
a[href^="http://"] { background: url(external-uri); padding-left: 12px; }
请注意,在这两种稍微更复杂的情况下,都应引用该值。这些对我来说在IE7中起作用。