使用 CSS 动画计数:仅动画一次而不是连续动画

时间:2021-05-30 20:36:20

标签: html css animation css-animations

假设我们有这个简单的 CSS 动画计数器:

div::after {
  font: 800 40px system-ui;
  content: counter(count);
  animation: counter 5s linear infinite;
  counter-reset: count 0;
}

@keyframes counter {
  0% {
    counter-increment: count 0;
  }
  10% {
    counter-increment: count 8;
  }
  20% {
    counter-increment: count 16;
  }
  30% {
    counter-increment: count 32;
  }
  40% {
    counter-increment: count 64;
  }
  50% {
    counter-increment: count 128;
  }
  60% {
    counter-increment: count 256;
  }
  70% {
    counter-increment: count 512;
  }
  80% {
    counter-increment: count 1024;
  }
  90% {
    counter-increment: count 2048;
  }
  100% {
    counter-increment: count 4000;
  }
}
<div></div>


如您所见,计数器在达到最终值 (4000) 时从零开始再次计数。

如何将计数器设置为只计数一次并保持其最终值(不再计数)?

1 个答案:

答案 0 :(得分:2)

infinite 更改为 forwards ....

<块引用>

forwards

目标将保留由执行期间遇到的最后一个关键帧设置的计算值。最后一个关键帧取决于 animation-direction 和 animation-iteration-count 的值:

div::after {
  font: 800 40px system-ui;
  content: counter(count);
  animation: counter 5s linear forwards;
  counter-reset: count 0;
}

@keyframes counter {
  0% {
    counter-increment: count 0;
  }
  10% {
    counter-increment: count 8;
  }
  20% {
    counter-increment: count 16;
  }
  30% {
    counter-increment: count 32;
  }
  40% {
    counter-increment: count 64;
  }
  50% {
    counter-increment: count 128;
  }
  60% {
    counter-increment: count 256;
  }
  70% {
    counter-increment: count 512;
  }
  80% {
    counter-increment: count 1024;
  }
  90% {
    counter-increment: count 2048;
  }
  100% {
    counter-increment: count 4000;
  }
}
<div></div>

相关问题