找不到“不等于”的 css 属性选择器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25287229/
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
Can't find a "not equal" css attribute selector
提问by Adrian Rosca
I want to target div elements where the attribute "foo" has a value.
我想定位属性“foo”具有值的 div 元素。
<div foo="x">XXX</div>
<div foo="">YYY</div>
I have tried this css, but it doesn't work:
我试过这个 css,但它不起作用:
[foo!='']
{
background: red;
}
回答by mehulmpt
Use the code like this:
使用这样的代码:
div:not([foo=''])
{
/* CSS Applied to divs having foo value Not nothing (or having a foo value assigned) */
}
回答by Curt
回答by moomoo
One problem with the above answer is that it will also select elements that do not have a "foo" attribute at all. Consider:
上述答案的一个问题是它还会选择根本没有“foo”属性的元素。考虑:
<div>No foo</div>
<div foo="">Empty foo</div>
<div foo="x">XXX</div>
<div foo="y">YYY</div>
<div foo="z">ZZZ</div>
div:not([foo='']) will select both the 1st and second div elements. If you just want div elements that have an attribute foo that is set to an empty string, you should use:
div:not([foo='']) 将选择第一个和第二个 div 元素。如果您只想要具有设置为空字符串的属性 foo 的 div 元素,则应使用:
div[foo]:not([foo=''])
One last example, if you want all elements with attribute foo that is not "y" or "z", you should use:
最后一个例子,如果你想要属性 foo 不是“y”或“z”的所有元素,你应该使用:
div[foo]:not([foo='y']):not([foo='z'])
And of course div can be left off altogether if selecting elements other than div.
当然,如果选择 div 以外的元素,可以完全不使用 div。