乐闻世界logo
搜索文章和话题

CSS 中 Not 伪类可以有多个参数吗?

7 个月前提问
3 个月前修改
浏览次数70

7个答案

1
2
3
4
5
6
7

是的,:not() 伪类选择器可以接受多个选择器作为它的参数。这表示可以指定多个条件来排除一组元素。在CSS选择器等级4的规范中,:not() 已经得到了扩展,允许它接受逗号分隔的选择器列表作为它的参数,这意味着它可以同时排除多种选择器匹配的元素。

例如,如果你想选择那些既不是类.class1也不是类.class2<p>元素,你可以这样写:

css
p:not(.class1, .class2) { /* 样式规则 */ }

在这个例子中,任何带有.class1.class2类的<p>元素都不会被选中,而其他所有<p>元素都会应用这里定义的样式。

需要注意的是,尽管CSS选择器等级4的规范支持多参数的:not(),但并非所有浏览器都实现了这一特性。因此,在使用时应该检查浏览器的兼容性情况,或者使用一些工具,如PostCSS等,来帮助转换这些现代CSS特性,以确保兼容旧版浏览器。在编写代码时,也应该考虑回退方案,以保证功能的正常使用。

2024年6月29日 12:07 回复

为什么:不只使用两个:not

shell
input:not([type="radio"]):not([type="checkbox"])

是的,这是故意的

2024年6月29日 12:07 回复

从 CSS 选择器 4 开始,在:not选择器中使用多个参数成为可能(请参见此处)。

在 CSS3 中,:not 选择器只允许 1 个选择器作为参数。在 4 级选择器中,它可以将选择器列表作为参数。

例子:

shell
/* In this example, all p elements will be red, except for the first child and the ones with the class special. */ p:not(:first-child, .special) { color: red; }

不幸的是,浏览器支持有点新

2024年6月29日 12:07 回复

如果您在项目中使用 SASS,我构建了这个 mixin 以使其按照我们希望的方式工作:

shell
@mixin not($ignorList...) { //if only a single value given @if (length($ignorList) == 1){ //it is probably a list variable so set ignore list to the variable $ignorList: nth($ignorList,1); } //set up an empty $notOutput variable $notOutput: ''; //for each item in the list @each $not in $ignorList { //generate a :not([ignored_item]) segment for each item in the ignore list and put them back to back $notOutput: $notOutput + ':not(#{$not})'; } //output the full :not() rule including all ignored items &#{$notOutput} { @content; } }

它可以通过两种方式使用:

选项 1:内联列出忽略的项目

shell
input { /*non-ignored styling goes here*/ @include not('[type="radio"]','[type="checkbox"]'){ /*ignored styling goes here*/ } }

选项 2:首先列出变量中被忽略的项目

shell
$ignoredItems: '[type="radio"]', '[type="checkbox"]' ; input { /*non-ignored styling goes here*/ @include not($ignoredItems){ /*ignored styling goes here*/ } }

任一选项的输出 CSS

shell
input { /*non-ignored styling goes here*/ } input:not([type="radio"]):not([type="checkbox"]) { /*ignored styling goes here*/ }
2024年6月29日 12:07 回复

我在这方面遇到了一些麻烦,“X:not():not()”方法对我不起作用。

我最终采用了这个策略:

shell
INPUT { /* styles */ } INPUT[type="radio"], INPUT[type="checkbox"] { /* styles that reset previous styles */ }

它并不那么有趣,但当 :not() 好斗时它对我有用。它并不理想,但很坚固。

2024年6月29日 12:07 回复

:not() 伪类选择器可以接受多个选择器作为它的参数。这表示可以指定多个条件来排除一组元素。在CSS选择器等级4的规范中,:not() 已经得到了扩展,允许它接受逗号分隔的选择器列表作为它的参数,这意味着它可以同时排除多种选择器匹配的元素。

例如,如果你想选择那些既不是类 .class1也不是类 .class2<p>元素,你可以这样写:

css
p:not(.class1, .class2) { /* 样式规则 */ }

在这个例子中,任何带有 .class1.class2类的 <p>元素都不会被选中,而其他所有 <p>元素都会应用这里定义的样式。

需要注意的是,尽管CSS选择器等级4的规范支持多参数的 :not(),但并非所有浏览器都实现了这一特性。因此,在使用时应该检查浏览器的兼容性情况,或者使用一些工具,如PostCSS等,来帮助转换这些现代CSS特性,以确保兼容旧版浏览器。在编写代码时,也应该考虑回退方案,以保证功能的正常使用。

2024年6月29日 12:07 回复

你的答案