CSS2属性选择器与正则表达式 [英] CSS2 Attribute Selectors with Regex
问题描述
CSS属性选择器允许选择元素基于属性值。不幸的是,我没有使用它们多年(主要是因为它们不支持所有的现代浏览器)。然而,我清楚地记得,我可以使用它们来用一个图标来装饰所有外部链接,通过使用类似如下代码:
CSS Attribute selectors allow the selection of elements based on attribute values. Unfortunately, I've not used them in years (mainly because they're not supported by all modern browsers). However, I remember distinctly that I was able to use them to adorn all external links with an icon, by using a code similar to the following:
a[href=http] {
background: url(external-uri);
padding-left: 12px;
}
上述代码不工作。 如何选择所有< a>
标签 href
属性以http
开头?官方的CSS规范(链接上面)甚至没有提到这是可能的。但我记得这样做。
The above code doesn't work. My question is: How does it work? How do I select all <a>
tags whose href
attribute starts with "http"
? The official CSS spec (linked above) doesn't even mention that this is possible. But I do remember doing this.
(注意:显而易见的解决方案是使用 class
属性为了区分,我想避免这是因为我对HTML代码的方式的影响很小,我可以编辑的是CSS代码。)
(Note: The obvious solution would be to use class
attributes for distinction. I want to avoid this because I have little influence of the way the HTML code is built. All I can edit is the CSS code.)
推荐答案
对于CSS 2.1,请参见 http://www.w3.org/TR/CSS21/selector.html#attribute-selectors
As for CSS 2.1, see 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]).
There's also a nifty test suite that that shows which selectors work in your browser.
对于您的示例,
a[href^=http]
{
background: url(external-uri);
padding-left: 12px;
}
不幸的是,IE不支持。
should do the trick. Unfortunately, it is not supported by IE.
这篇关于CSS2属性选择器与正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!