如何将CSS关键帧名称作为变量传递?

时间:2020-08-01 23:40:20

标签: css css-variables

我有一个CSS动画关键帧:

  @keyframes first-movement {
    0%, 100% {
      opacity: 0;
      transform: scale(0) rotate(0deg);
    }
    20%, 99% {
      opacity: 1;
      transform: scale(1) rotate(180deg);
    }
  }

当我通常使用它时,一切正常

  rect {
    animation-name: first-movement;
    animation-timing-function: linear;
    animation-duration: 8s;
    animation-iteration-count: infinite;
    transform-origin: 40px 40px;
  }

但是当我尝试作为CSS var发送时,它不起作用

  rect {
    animation-name: var(--main-animation);
    animation-timing-function: linear;
    animation-duration: 8s;
    animation-iteration-count: infinite;
    transform-origin: 40px 40px;
  }

这是我可以分配var的方式,

  #load-area > use:nth-child(1) {
    --main-animation: first-movement;
  }

它不会抛出错误或进行任何线索调查,这是哪个错误?

更新: 我添加了完整的代码,删除标记的行以破坏它。

正如我所提到的,我使用animation-duration来做到这一点,并且效果很好,但是计算时间更加复杂,而是在必要的时机创建新的关键帧(我有五个关键帧)。

更新2: 这是一个Chrome BUG,该代码可在Firefox上完美运行 enter image description here

      @keyframes first {
        0%, 100% {
          opacity: 0;
          transform: scale(0) rotate(0deg);
        }
        20%, 99% {
          opacity: 1;
          transform: scale(1) rotate(180deg);
        }
      }
      
      @keyframes second {
        0%, 20%, 100% {
          opacity: 0;
          transform: scale(0) rotate(0deg);
        }
        40%, 99% {
          opacity: 1;
          transform: scale(1) rotate(180deg);
        }
      }
      
       #circle,
      #cross,
      #square,
      #triangle {
        opacity: 0;
      }

      rect {
        animation-name: var(--main-animation);
        animation-timing-function: linear;
        animation-duration: 8s;
        animation-iteration-count: infinite;
        transform-origin: 40px 40px;
      }

      #load-area > use:nth-child(1) {
        --main-animation: first;
      }
      
      #load-area > use:nth-child(1) {
        --main-animation: second;
      }
    <div style="background-color: aliceblue">
      <svg viewBox="-20 -20 600 200" id="main">
        <defs id="test">

          <rect width="80" height="80" id="circle" fill="red" />
          <rect width="80" height="80" id="square" fill="pink" />
          <rect width="80" height="80" id="cross" fill="blue" />
          <rect width="80" height="80" id="triangle" fill="green" />
        </defs>

        <g id="load-area">
          <use x="0" xlink:href="#circle" />
          <use x="100" xlink:href="#square" />
          <use x="200" xlink:href="#cross" />
          <use x="300" xlink:href="#triangle" />
        </g>
      </svg>
    </div>

0 个答案:

没有答案