css属性选择器不匹配动态添加的类名

时间:2015-03-08 12:43:29

标签: css css-selectors

我正在使用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;
}

1 个答案:

答案 0 :(得分:2)

$=运算符匹配整个属性的结尾,因此如果您定位的类不是元素的最后一个(比如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;
}

当组合两个类(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;
}

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