CSS 正则表达式选择器匹配一个或另一个条件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23963073/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
CSS regex selector match one OR another condition?
提问by Danny
I'd like to match when /(\sclassName|^className)/
is satisfied, but when selecting css. Hypothetically I would use like:
我想在/(\sclassName|^className)/
满足时匹配,但是在选择 css 时。假设我会使用:
[class(^|\s)='className'] {
font-size: 5000px;
}
I've found this resource, which is very nice: The Skinny on CSS Attribute Selectors, but it doesn't mention this use case.
我找到了这个非常好的资源:The Skinny on CSS Attribute Selectors,但它没有提到这个用例。
I just want to match "icon-" in the following 2 examples, but not the 3rd.
我只想在以下两个示例中匹配“icon-”,而不是第三个示例。
Here, this can be achieved with [class^='icon-]
在这里,这可以通过 [class^='icon-]
<div class='icon-something another-class'>
Here, this can be achieved with [class~='icon-']
, but this does not match when 'icon-' is at the very beginning of the class string:
在这里,这可以通过 来实现[class~='icon-']
,但是当 'icon-' 位于类字符串的最开头时,这不匹配:
<div class='another-class icon-something'>
I do not want to match this, with -icon in the middle of a string. I believe *=
will match this one, as will |=
:
我不想将它与字符串中间的 -icon 匹配。我相信*=
会匹配这个,因为|=
:
<div class='another-icon-class another-class'>
回答by Paul Roub
You'll need to use two separate selectors with the same rule. CSS selectors don't really support alternation.
您需要使用两个具有相同规则的独立选择器。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>
回答by James Donnelly
You can use the following selectors to select any element whose class either starts with "icon-"
or contains " icon-"
(note the space at the start):
您可以使用以下选择器来选择其类以开头"icon-"
或包含的任何元素" icon-"
(注意开头的空格):
[class^="icon-"], [class*=" icon-"] { ... }