CSS动画自定义属性/变量

Joh*_*150 4 html css css3 css-animations css-variables

我一直在努力使它工作一段时间。

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

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

我有什么想念的吗?我已经检查了是否可以在其中使用CSS变量,@keyframes并且可以肯定。动画中它们的唯一问题似乎是它们之间没有插值,但是它们突然切换,在这种情况下这不是问题。

@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);
}
Run Code Online (Sandbox Code Playgroud)
<div id="test">
    <div></div>
</div>
Run Code Online (Sandbox Code Playgroud)

vsy*_*ync 10

这可以通过使用(在编写本文时,没有得到很好的支持)定义变量来实现@property,它允许声明类型并允许浏览器“理解”,例如,某个属性(变量)是一个数字,然后它可以逐渐动画/转换该变量是可能的。

示例代码:

@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;  /* "forwards pesists the last keyframe styles */
  background: rgba(0 0 0 / var(--opacity));
}
Run Code Online (Sandbox Code Playgroud)

当前允许的类型包括:

  • length
  • number
  • percentage
  • length-percentage
  • color
  • image
  • url
  • integer
  • angle
  • time
  • resolution
  • transform-list
  • transform-function
  • custom-ident (自定义标识符字符串)

有用的文章:

  1. https://web.dev/at-property/#writing-houdini-custom-properties
  2. https://css-tricks.com/using-property-for-css-custom-properties
  3. 很酷的 Houdini 演示


Tem*_*fif 6

规范中所述:

值得注意的是,它们甚至可以进行过渡或设置动画,但是由于UA 无法解释其内容,因此它们始终使用“对50%翻转”的行为,该行为用于无法智能插值的任何其他一对值。但是,@keyframes规则中使用的 任何自定义属性都会受到动画污染,这会影响通过animation属性中的var()函数进行引用时如何对待它。


因此,即使您在关键帧中使用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;
  
}
Run Code Online (Sandbox Code Playgroud)
<div id="test">
  <div></div>
</div>
Run Code Online (Sandbox Code Playgroud)

顺便说一下,如果将其用作,则可以使其正常工作,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;
}
Run Code Online (Sandbox Code Playgroud)
<div id="test">
  <div></div>
</div>
Run Code Online (Sandbox Code Playgroud)