問題描述
是否可以在 :not 選擇器中包含嵌套值?例如:
Is it possible to have nested values inside the :not selector? For eg:
:not(div > div)
每當(dāng)我嘗試它時,它似乎都不起作用.也許您需要以另一種我還沒有想到的方式使用它?到目前為止,在我看到的所有示例中,您只能在此選擇器中使用一個值.
Whenever I tried it, it does not seem to work. Perhaps you need to use it another way which I have not figured out? So far, in all the examples I see, you can only use one value inside this selector.
推薦答案
:not()
一次只接受一個簡單的選擇器;Selectors 3 規(guī)范中提到了這一點(diǎn):
:not()
only accepts one simple selector at a time; this is mentioned in the Selectors 3 spec:
否定偽類 :not(X)
是一個采用 簡單選擇器(不包括否定偽類本身)作為參數(shù).它表示其參數(shù)未表示的元素.
The negation pseudo-class,
:not(X)
, is a functional notation taking a simple selector (excluding the negation pseudo-class itself) as an argument. It represents an element that is not represented by its argument.
您的示例中的簡單選擇器將是您擁有的兩個 div
標(biāo)記.其他簡單的選擇器包括類選擇器、ID 選擇器、屬性選擇器和偽類.它不接受多個簡單的選擇器,也不接受 >
或空格等組合符.
The simple selectors in your example would be the two div
tokens that you have. Other simple selectors include class selectors, ID selectors, attribute selectors and pseudo-classes. It does not accept more than one simple selector, nor does it accept combinators like >
or space.
根據(jù)您要準(zhǔn)確選擇的元素,可能無法排除 div >div
:
Depending on which elements you're trying to select exactly, there may not be a way to exclude div > div
:
如果您只想選擇
div
的子元素,而這些元素本身不是div
,請改用:
If you only want to select elements that are children of a
div
, that are themselves notdiv
, use this instead:
div > :not(div)
如果您只想選擇父元素不是 div
的 div
元素,請改用:
If you only want to select div
elements whose parent element is not a div
, use this instead:
:not(div) > div
如果你想單獨(dú)使用這個否定,選擇所有個其他元素,那么只使用一個選擇器是沒有辦法的.
If you want to use this negation by itself, selecting all other elements, then there isn't a way using just a selector.
我能想到的唯一其他可行的 CSS 解決方法是在沒有 :not()
表達(dá)式的情況下將樣式應(yīng)用于您想要的元素,然后為 div > 撤消它們.div
.這適用于您嘗試定位的任何一組元素;缺點(diǎn)是并非所有屬性都可以輕松重置.
The only other viable workaround in CSS that I can think of is to apply styles to the elements you want without the :not()
expression, then undo them for div > div
. This works for any set of elements you're trying to target; the disadvantage is that not all properties can be easily reset.
或者,如果您使用 jQuery,它確實支持 :not(div > div)
與 CSS 版本不同,您可以將選擇器放在腳本中,例如,讓 jQuery 將類名應(yīng)用于那些然后元素在您的 CSS 中定位該類.
Alternatively, if you're using jQuery, which does support :not(div > div)
unlike the CSS version, you can place the selector in a script and, for instance, have jQuery apply a class name to those elements then target that class in your CSS.
這篇關(guān)于嵌套在 css :not() 選擇器中的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!