带有正则表达式的 CSS2 属性选择器

Posted

技术标签:

【中文标题】带有正则表达式的 CSS2 属性选择器【英文标题】:CSS2 Attribute Selectors with Regex 【发布时间】:2010-09-08 03:23:05 【问题描述】:

CSS Attribute selectors 允许根据属性值选择元素。不幸的是,我已经好几年没有使用它们了(主要是因为并非所有现代浏览器都支持它们)。但是,我清楚地记得,我可以使用它们来装饰所有带有图标的外部链接,方法是使用类似于以下的代码:

a[href=http] 
    background: url(external-uri);
    padding-left: 12px;

上面的代码不起作用。我的问题是:它是如何工作的?如何选择所有href 属性以"http" 开头的<a> 标签?官方的 CSS 规范(上面链接)甚至没有提到这是可能的。但我确实记得这样做过。

(注意:显而易见的解决方案是使用 class 属性进行区分。我想避免这种情况,因为我对 html 代码的构建方式影响不大。我可以编辑是 CSS 代码。)

【问题讨论】:

【参考方案1】:

Antti 的回答足以选择其 href 以 http 开头的锚点,并完美概括了可用的 CSS2 regex-esque 属性选择器,如下所示:

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 :not pseudo class selector 和新的*= substring syntax 选择所有传出链接的适当的更新方法,以确保它忽略可能仍以 http 开头的任何内部链接强>:

a[href^=http]:not([href*="yourdomain.com"])

    background: url(external-uri);
    padding-left: 12px;

*请注意,IE 不支持此功能,至少 IE8 不支持。谢谢,IE,你是最好的:P

【讨论】:

【参考方案2】:

至于 CSS 2.1,见http://www.w3.org/TR/CSS21/selector.html#attribute-selectors

执行摘要:

属性选择器可以通过四种方式匹配: [阿特] 当元素设置“att”属性时匹配,无论该属性的值如何。 [att=val] 当元素的“att”属性值正好是“val”时匹配。 [att~=val] 当元素的“att”属性值为空格分隔的列表时匹配 “words”,其中之一就是“val”。如果使用此选择器,则 value 不能包含空格(因为它们是由空格分隔的)。 [att|=val] 当元素的“att”属性值是连字符分隔的列表时匹配 “单词”,以“val”开头。比赛总是从比赛开始 属性值。这主要是为了允许语言子代码匹配 (例如,HTML 中的“lang”属性),如 RFC 3066 ([RFC3066]) 中所述。

CSS3 also defines a list of selectors,但the compatibility varies hugely。

还有 a nifty test suite 显示哪些选择器在您的浏览器中工作。

至于你的例子,

a[href^=http]

    background: url(external-uri);
    padding-left: 12px;

应该可以解决问题。不幸的是,IE 不支持它。

【讨论】:

我以为IE7确实支持它?正是我读到的……知道 IE 可能并非如此【参考方案3】:

请注意,在 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 中有效。

【讨论】:

以上是关于带有正则表达式的 CSS2 属性选择器的主要内容,如果未能解决你的问题,请参考以下文章

css2选择器

CSS2伪类选择器要点

jQuery 选择器正则表达式

jQuery选择器正则表达式

jQuery 属性选择器

jQuery 属性选择器