【问题标题】:CSS regex selector match one OR another condition?CSS 正则表达式选择器匹配一个或另一个条件?
【发布时间】:2017-12-22 07:02:07
【问题描述】:

我想在满足/(\sclassName|^className)/ 时匹配,但在选择css 时。假设我会这样使用:

[class(^|\s)='className'] {
  font-size: 5000px;
}

我找到了这个资源,非常好:The Skinny on CSS Attribute Selectors,但它没有提到这个用例。

我只想匹配以下 2 个示例中的“icon-”,而不是第 3 个。

这里,这可以通过[class^='icon-]实现

<div class='icon-something another-class'>

这里,这可以通过[class~='icon-'] 来实现,但是当 'icon-' 位于类字符串的最开始时,这不匹配:

<div class='another-class icon-something'>

我不想匹配这个, -icon 在字符串中间。我相信*= 会匹配这个,|= 也会匹配:

<div class='another-icon-class another-class'>

【问题讨论】:

    标签: css regex


    【解决方案1】:

    您需要使用具有相同规则的两个单独的选择器。 CSS 选择器并不真正支持交替。

    [class^='icon-'], [class*=' icon-'] {
      /* ... */
    }
    

    div {
      color: red;
    }
    
    [class^='icon-'], [class*=' icon-'] {
      color: green;
    }
    <div class='icon-something another-class'>should match</div>
    <div class='another-class icon-something'>should match</div>
    <div class='another-icon-class another-class'>should not match</div>

    【讨论】:

    • 啊,在 * 匹配器前面放一个空格是个好主意。好的,感谢您首先使用此解决方案,您得到检查!
    【解决方案2】:

    您可以使用以下选择器来选择类以"icon-" 开头或包含" icon-" 的任何元素(注意开头的空格):

    [class^="icon-"], [class*=" icon-"] { ... }
    

    JSFiddle demo.

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-16
      相关资源
      最近更新 更多