CSS属性的选择 允许选择的因素的基础上属性的价值观。不幸的是,我不用他们在年(主要是因为他们不支持通过所有现代化的浏览器)。然而,我记得清楚,我能用它们来装饰的所有外部的链接,有一个图标,通过使用代码类似于以下内容:

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

上述代码不起作用。我的问题是: 它是如何工作的? 我怎么选择所有 <a> 标签的 href 属性始 "http"?官方CSS规范(联段)甚至没有说这是可能的。但我记得这样做。

(注意到:显而易见的解决方案将使用 class 属性的区别。我想避免这一点,因为我有一点影响的方式HTML码是建立。所有我可以编辑是CSS代码。)

有帮助吗?

解决方案

作为CSS2.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的答案是足够的用于选择锚的其href开始 http 并给出一个完美的破败的可CSS2 regex式 属性的选择,就像这样:

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 :不 伪类选择 以及新的 *= substring语法 要确保它无视任何内部的链接,仍然可以开始 http:

a[href^=http]:not([href*="yourdomain.com"])
{
    background: url(external-uri);
    padding-left: 12px;
}

*请注意,这是不支持即,至少IE8.谢谢,即,你是最好的:P

请注意,在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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top