纯 CSS 中视口中元素的动画计数

问题描述 投票:0回答:1

我的目标是在数字进入视口后立即启动从 0 到 100 的数字计数器。

使用我当前的解决方案,我有两个问题:

  1. 数到 100 后数字跳回 0
  2. 计数并不是在元素进入视口时“开始”,而是取决于滚动状态。它会计算用户滚动的距离。

这是我的代码:

CSS:

.number {
    animation-name: counter;
    animation-duration: 5s; 
    animation-timing-function: ease-in-out; 
    animation-delay: 0s;
    animation-direction: normal;
    animation-iteration-count: 1;
    animation-fill-mode: none;
    animation-timeline: view();
    counter-reset: num var(--num);
    font: 800 40px system-ui;
    padding: 2rem;
  }
  .number::after {
    content: counter(num);
  }
  
  @keyframes counter {
    from {
      --num: 0;
    }
    to {
      --num: 100;
    }
  }

HTML:

<span class="number"></span>
css animation numbers css-animations
1个回答
0
投票

您需要更新一些内容才能使其正常工作。

  1. @property
    块中定义 num 变量
  2. 摆脱
    animation-timeline
  3. 简化您的
    animation
    forwards
    将在最后一帧停止填充模式)。

类似以下内容:

@property --num {
  syntax: "<integer>";
  initial-value: 0;
  inherits: false;
}

.number {
  animation: counter 5s forwards ease-in-out;
  counter-reset: num var(--num);
  font: 800 40px system-ui;
  padding: 2rem;
}

.number::after {
  content: counter(num);
}

@keyframes counter {
  from {
    --num: 0;
  }
  to {
    --num: 100;
  }
}

<span class="number"></span>

© www.soinside.com 2019 - 2024. All rights reserved.