You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

纯CSS实现元素进入视口时数字计数动画问题求助

解决方案

修正后的代码

HTML

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

CSS

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

.number {
  animation: none; /* 初始不播放动画 */
  animation-duration: 5s; 
  animation-timing-function: ease-in-out; 
  animation-delay: 0s;
  animation-direction: normal;
  animation-iteration-count: 1;
  animation-fill-mode: forwards; /* 动画结束后保持最终状态 */
  counter-reset: num var(--num);
  font: 800 40px system-ui;
  padding: 2rem;
}

.number.animate {
  animation-name: counter; /* 进入视口后添加类触发动画 */
}

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

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

JavaScript

const numberElement = document.querySelector('.number');

const observer = new IntersectionObserver((entries) => {
  entries.forEach(entry => {
    if (entry.isIntersecting) {
      numberElement.classList.add('animate');
      observer.unobserve(numberElement); // 确保只触发一次
    }
  });
}, {
  threshold: 0.1 // 元素10%进入视口时启动动画
});

observer.observe(numberElement);

关键修改说明

  • 解决计数跳回0的问题:把animation-fill-mode设为forwards,让动画结束后保留最终帧的--num: 100状态,不会重置回初始值。
  • 解决视口触发时机问题:
    1. 移除animation-timeline: view(),这个属性会让动画随滚动进度推进,而非元素进入视口立即启动。
    2. 用Intersection Observer监听元素,当元素进入视口时添加animate类触发动画,并且只执行一次。

内容的提问来源于stack exchange,提问作者smaica

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 15:42:36