js 实现滚动数字
实现滚动数字效果
方法一:使用 CSS 动画和 JavaScript
HTML 结构:
<div class="counter" data-target="1000">0</div>
CSS 样式:
.counter {
font-size: 24px;
font-weight: bold;
transition: color 0.3s;
}
JavaScript 代码:

function animateCounter(element, target, duration = 2000) {
const start = parseInt(element.textContent);
const increment = target / (duration / 16);
let current = start;
const updateCounter = () => {
current += increment;
if (current < target) {
element.textContent = Math.floor(current);
requestAnimationFrame(updateCounter);
} else {
element.textContent = target;
}
};
updateCounter();
}
document.querySelectorAll('.counter').forEach(counter => {
const target = parseInt(counter.getAttribute('data-target'));
animateCounter(counter, target);
});
方法二:纯 JavaScript 实现
function scrollNumber(element, finalNumber, duration = 1000) {
const startTime = performance.now();
const startNumber = parseInt(element.textContent) || 0;
const updateNumber = (timestamp) => {
const elapsed = timestamp - startTime;
const progress = Math.min(elapsed / duration, 1);
const currentNumber = Math.floor(progress * (finalNumber - startNumber) + startNumber);
element.textContent = currentNumber;
if (progress < 1) {
requestAnimationFrame(updateNumber);
}
};
requestAnimationFrame(updateNumber);
}
// 使用示例
const counter = document.getElementById('counter');
scrollNumber(counter, 1000);
方法三:带缓动函数的实现
function easeOutQuad(t) {
return t * (2 - t);
}
function smoothScrollNumber(element, target, duration = 1000) {
let start = null;
const initial = parseInt(element.textContent) || 0;
const distance = target - initial;
const step = (timestamp) => {
if (!start) start = timestamp;
const progress = timestamp - start;
const percentage = Math.min(progress / duration, 1);
const eased = easeOutQuad(percentage);
element.textContent = Math.floor(initial + distance * eased);
if (percentage < 1) {
requestAnimationFrame(step);
}
};
requestAnimationFrame(step);
}
方法四:支持小数滚动的实现
function decimalScroll(element, target, duration = 1000, decimals = 0) {
const start = parseFloat(element.textContent) || 0;
const distance = target - start;
let startTime = null;
const animate = (timestamp) => {
if (!startTime) startTime = timestamp;
const elapsed = timestamp - startTime;
const progress = Math.min(elapsed / duration, 1);
const currentValue = start + distance * progress;
element.textContent = currentValue.toFixed(decimals);
if (progress < 1) {
requestAnimationFrame(animate);
}
};
requestAnimationFrame(animate);
}
注意事项
- 性能优化:使用 requestAnimationFrame 代替 setInterval 可以获得更流畅的动画效果
- 数字格式化:对于大数字可以考虑添加千分位分隔符
- 容器宽度:确保容器足够宽以容纳滚动时的数字变化
- 浏览器兼容性:现代浏览器都支持这些方法,如需支持旧版浏览器可能需要 polyfill
这些方法可以根据实际需求进行调整,例如添加回调函数、自定义缓动效果或结合其他动画效果。






