CSS Attribute selectors允许根据属性值选择元素。不幸的是,我已经很多年没有使用它们了(主要是因为所有现代浏览器都不支持它们)。但是,我清楚地记得我能够使用它们来用图标装饰所有外部链接,方法是使用类似于以下的代码:
a[href=http] {
background: url(external-uri);
padding-left: 12px;
}
上面的代码不起作用。我的问题是:它是如何工作的?我如何选择所有 <a>
href
的标签属性以 "http"
开头?官方 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 also defines a list of selectors, but the compatibility varies hugely.
There's also a nifty test suite that that shows which selectors work in your browser.
As for your example,
a[href^=http]
{
background: url(external-uri);
padding-left: 12px;
}
应该可以解决问题。很遗憾,IE 不支持它。
关于带正则表达式的 CSS2 属性选择器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49368/