纯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状态,不会重置回初始值。 - 解决视口触发时机问题:
- 移除
animation-timeline: view(),这个属性会让动画随滚动进度推进,而非元素进入视口立即启动。 - 用Intersection Observer监听元素,当元素进入视口时添加
animate类触发动画,并且只执行一次。
- 移除
内容的提问来源于stack exchange,提问作者smaica
相关产品推荐
相关产品推荐

