css 属性选择器与动态添加的 class 名称不匹配

css attribute selector not matching dynamically added class names

我正在使用 React 的 CSS 动画插件,当我使用它们提供的类名时一切正常。

.quote-enter {
  opacity: 0.01;
  transition: opacity .25s ease-in;
}

.quote-enter.quote-enter-active {
  opacity: 1;
}

.quote-leave {
  opacity: 1;
  transition: opacity .25s ease-in;
}

.quote-leave.quote-leave-active {
  opacity: 0.01;
}

但是当我尝试将其转换为属性选择器方法以捕获应该设置动画的每个组件实例时,它不起作用,没有匹配的选择器。

[class$='-enter'] {
  opacity: 0.01;
  transition: opacity .25s ease-in;
}

[class$='-enter'][class$='-enter-active'] {
  opacity: 1;
}

[class$='-leave'] {
  opacity: 1;
  transition: opacity .25s ease-in;
}

[class$='-leave'][class$='-leave-active'] {
  opacity: 0.01;
}

$= 运算符匹配整个属性的末尾,因此如果您定位的 class 不是元素的最后一个(比如 class="whatever-enter other-class"),选择器不匹配。

你可以试试这个:

[class$='-enter'], [class*='-enter '] {
  opacity: 0.01;
  transition: opacity .25s ease-in;
}
[class$='-leave'], [class*='-leave '] {
  opacity: 1;
  transition: opacity .25s ease-in;
}

组合两个 classes(2*2 = 4 个选择器)时会变得更复杂,所以也许你最好还是单独使用 *= 运算符:

[class*='-enter'] {
  opacity: 0.01;
  transition: opacity .25s ease-in;
}

[class*='-enter'][class*='-enter-active'] {
  opacity: 1;
}

[class*='-leave'] {
  opacity: 1;
  transition: opacity .25s ease-in;
}

[class*='-leave'][class*='-leave-active'] {
  opacity: 0.01;
}

只要您没有以这些后缀结尾的任何其他 classes,这将有效。