CSS 动画自定义 properties/variables

CSS animate custom properties/variables

一段时间以来,我一直在努力让它发挥作用。

关键是内部 div 会有一些形状,而且可能不止一个(这就是我使用 nth-child 选择器的原因)。 这个内部 div 应该显示然后再次隐藏一段时间。 问题是,我想在一个动画中为所有(后来的)多个内部 div 设置动画。为此,我想我可以使用 CSS 变量,但这似乎不起作用。

我在这个例子中试图实现的是内部 div 基本上只是通过使用变量来闪烁。但是我在 Firefox 中的结果只是一个黑框。

我错过了什么吗?我已经查过是否可以在 @keyframes 中使用 CSS 变量,当然可以。 它们在动画中的唯一问题似乎是它们之间没有插值,而是它们突然切换,这在这种情况下不是问题。

@keyframes test{
    from{
        --one: 0;
    }
    to{
        --one: 1;
    }
}

#test{
    width: 100px;
    height: 200px;
    background-color: black;
    animation: test 1s infinite;
}
#test :nth-child(1){
    width: 20px;
    height: 20px;
    margin: auto;
    background-color: white;
    opacity: var(--one,0);
}
<div id="test">
    <div></div>
</div>

specification 中所述:

Animatable: no

还有

Notably, they can even be transitioned or animated, but since the UA has no way to interpret their contents, they always use the "flips at 50%" behavior that is used for any other pair of values that can’t be intelligently interpolated. However, any custom property used in a @keyframes rule becomes animation-tainted, which affects how it is treated when referred to via the var() function in an animation property.


所以即使你在关键帧中使用 opacityvar() 它也不会动画:

@keyframes test {
  from {
    --one:0;
    opacity: var(--one);
  }
  to {
    opacity: var(--one);
    --one: 1;
  }
}

#test {
  width: 100px;
  height: 200px;
  background-color: black;
}

#test :nth-child(1) {
  width: 20px;
  height: 20px;
  margin: auto;
  background-color: white;
  animation: test 1s  infinite;
  
}
<div id="test">
  <div></div>
</div>

顺便说一句,如果您将它用作 transition,您可以使它工作,因为在这种情况下,您将对不透明度应用过渡,而不是自定义 属性:

#test {
  width: 100px;
  height: 200px;
  background-color: black;
}

#test:hover {
  --one:1;
}

#test :nth-child(1) {
  width: 20px;
  height: 20px;
  margin: auto;
  background-color: white;
  opacity: var(--one,0);
  transition:1s all;
}
<div id="test">
  <div></div>
</div>

这可以通过使用(在撰写本文时,而不是 well-supported)@property 定义变量来实现,它允许声明 types 并且允许浏览器“理解”,例如,某个属性(变量)是一个数字,然后它可以逐渐animate/transition那个变量。

示例代码:

@property --opacity {
  syntax: '<number>'; /* <- defined as type number for the transition to work */
  initial-value: 0;
  inherits: false;
}

@keyframes fadeIn {
  50% {--opacity: 1}
}

html {
  animation: 2s fadeIn infinite;
  background: rgba(0 0 0 / var(--opacity));
}

当前允许的类型包括:

lengthnumberpercentagelength-percentagecolorimageurlintegerangletimeresolutiontransform-listtransform-functioncustom-ident(标识符字符串)


有用的文章:

  1. https://web.dev/at-property/#writing-houdini-custom-properties
  2. https://css-tricks.com/using-property-for-css-custom-properties
  3. Cool Houdini demos