JavaScript 数字滚动是一种常见的前端动画效果,用于在网页上动态显示数字的变化。这种效果通常用于计数器、实时统计数据展示等场景。
数字滚动是通过 JavaScript 定时器(如 setInterval
或 requestAnimationFrame
)逐步更新页面上的数字来实现的。每次定时器触发时,数字会按设定的步长增加或减少,直到达到目标值。
以下是一个简单的递增数字滚动的示例代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>数字滚动示例</title>
<style>
#counter {
font-size: 48px;
text-align: center;
margin-top: 50px;
}
</style>
</head>
<body>
<div id="counter">0</div>
<script>
const counterElement = document.getElementById('counter');
let currentValue = 0;
const targetValue = 1000;
const step = 10; // 每次增加的数值
function updateCounter() {
if (currentValue < targetValue) {
currentValue += step;
counterElement.textContent = currentValue;
requestAnimationFrame(updateCounter);
} else {
currentValue = targetValue;
counterElement.textContent = currentValue;
}
}
updateCounter();
</script>
</body>
</html>
requestAnimationFrame
代替 setInterval
,以确保动画与浏览器的刷新率同步。通过以上方法,可以有效地实现和控制 JavaScript 数字滚动效果,提升用户体验。
领取专属 10元无门槛券
手把手带您无忧上云