js 实现滚动数字
实现滚动数字的 JavaScript 方法
使用 CSS 动画和 JavaScript 控制
通过 CSS 的 transform 和 transition 属性实现数字滚动效果,JavaScript 用于动态更新数值。
function animateValue(element, start, end, duration) {
const range = end - start;
let current = start;
const increment = end > start ? 1 : -1;
const stepTime = Math.abs(Math.floor(duration / range));
const timer = setInterval(() => {
current += increment;
element.textContent = current;
if (current === end) clearInterval(timer);
}, stepTime);
}
// 调用示例
const counter = document.getElementById('counter');
animateValue(counter, 0, 100, 2000);
使用 requestAnimationFrame 平滑滚动
requestAnimationFrame 提供更流畅的动画效果,适合高性能要求的场景。
function smoothScrollNumber(element, target, duration = 1000) {
const start = parseInt(element.textContent) || 0;
const startTime = performance.now();
function updateNumber(timestamp) {
const elapsed = timestamp - startTime;
const progress = Math.min(elapsed / duration, 1);
const value = Math.floor(start + (target - start) * progress);
element.textContent = value;
if (progress < 1) requestAnimationFrame(updateNumber);
}
requestAnimationFrame(updateNumber);
}
// 调用示例
smoothScrollNumber(document.getElementById('counter'), 100);
使用第三方库(如 CountUp.js)
对于复杂需求,可直接使用现成库如 CountUp.js。
<script src="https://cdn.jsdelivr.net/npm/countup.js@2.0.8/dist/countUp.min.js"></script>
<script>
const options = {
duration: 2,
separator: ','
};
const counter = new CountUp('counter', 0, 100, 0, 2, options);
counter.start();
</script>
实现数字翻转效果
模拟物理翻转卡片的效果,需配合 CSS 3D 变换。
function flipNumber(element, newValue) {
const current = element.textContent;
const flipContainer = document.createElement('div');
flipContainer.className = 'flip-container';
const flip = document.createElement('div');
flip.className = 'flip';
flip.textContent = current;
const flipNext = document.createElement('div');
flipNext.className = 'flip next';
flipNext.textContent = newValue;
flipContainer.appendChild(flip);
flipContainer.appendChild(flipNext);
element.innerHTML = '';
element.appendChild(flipContainer);
setTimeout(() => flip.classList.add('active'), 10);
setTimeout(() => {
element.textContent = newValue;
}, 500);
}
// 调用示例
flipNumber(document.getElementById('counter'), 5);
对应 CSS 样式:
.flip-container {
position: relative;
display: inline-block;
width: 1em;
height: 1.2em;
overflow: hidden;
}
.flip {
position: absolute;
width: 100%;
height: 100%;
text-align: center;
transition: transform 0.4s;
backface-visibility: hidden;
transform-style: preserve-3d;
}
.flip.next {
transform: rotateX(180deg);
}
.flip.active {
transform: rotateX(-180deg);
}
注意事项
- 性能优化:大数据量滚动时建议使用
requestAnimationFrame而非setInterval - 移动端兼容:检查 CSS 变换的浏览器前缀支持情况
- 可访问性:确保动态内容能被屏幕阅读器识别,可添加
aria-live属性






