【问题标题】:How to select all non-empty anchor links with a CSS selector?如何使用 CSS 选择器选择所有非空锚链接?
【发布时间】:2017-11-03 15:44:52
【问题描述】:

嘿,我正在寻找一个 CSS 选择器来选择所有非空锚链接,其中锚本身不为空。

我已经有一个选择器来选择所有具有锚属性的链接 - 参见这个例子:

a[href*=\#] {
  background-color:#f00;
}
<div id="sample">
<p>
Hey bro, yesterday I was walking about 50 
<a href="http://www.example.com">example</a> 
kilometers down this shiny road. 
After watching <a href="#friends">my friends</a> smoking a 
<a href="#">shiny cigarette</a> the air became dark 
<a href="http://example.com/#">and</a>
 my fancyness 
<a href="http://www.example.com/#inc">increased</a>.
</p>
</div>

但是我想要的是选择所有带有 href="#something" 的锚点,同时排除所有 href="whatever#" 的锚点。

这样“闪亮的香烟”和“和”就不会被选中。

你能帮我解决这个问题吗?

【问题讨论】:

    标签: html css css-selectors


    【解决方案1】:

    a[href*=\#]:not([href$=\#]) {
      background-color: #f00;
    }
    <div id="sample">
      <p>
        Hey bro, yesterday I was walking about 50
        <a href="http://www.example.com">example</a> kilometers down this shiny road. After watching <a href="#friends">my friends</a> smoking a
        <a href="#">shiny cigarette</a> the air became dark
        <a href="http://example.com/#">and</a> my fancyness
        <a href="http://www.example.com/#inc">increased</a>.
      </p>
    </div>

    在上面的示例中,所有包含 (*) # 的属性值都被选中,但那些 ($) # 结尾的值被排除在外。

    a[href*="value"] - the attribute value *contains* the specified value
    a[href$="value"] - the attribute value *ends with* the specified value
    a[href^="value"] - the attribute value *starts with* the specified value
    a[href="value"]  - the attribute value *matches exactly* the specified value
    

    更多:https://www.w3.org/TR/css3-selectors/#selectors

    【讨论】:

      【解决方案2】:
      a[href^=\#] {
        background-color:#f00;
      }
      

      ^= 运算符表示以

      开头

      这是你想要的吗?

      去掉#后面的空

      a[href^=\#]:not([href=\#]) {
            background-color:#f00;
          }
      

      【讨论】:

      • 为什么要投反对票?我错过了你所拥有的?您需要以 # 开头但在 or 之后不为空的链接?
      • 对不起兄弟,我没有投反对票。有人对这个问题投了反对票,所有答案都不知道为什么。不过迈克尔早些时候给了我正确的答案。
      猜你喜欢
      • 2014-03-01
      • 2016-07-24
      • 2018-06-22
      • 2020-09-06
      • 1970-01-01
      • 1970-01-01
      • 2014-06-04
      • 2013-06-03
      • 2016-05-06
      相关资源
      最近更新 更多