数字从0到指定数字的滚动动效,直接上代码;
H5
<!DOCTYPE html>
<html>
<head><style>/* 设置数字显示的样式 */.counter {font-weight:700;font-size: 36px;color: #333;}</style>
</head>
<body><div class="counter">0</div><script>const targetNumber = 1000; // 指定的目标数字const duration = 10000; // 动画持续时间,单位为毫秒const counterElement = document.querySelector('.counter'); // 获取数字显示的元素let startTime = null; // 动画开始时间function step(timestamp) {console.log(timestamp)if (!startTime) startTime = timestamp; // 记录动画开始时间const progress = timestamp - startTime; // 计算动画进度console.log(progress,timestamp,startTime)// 根据动画进度计算当前数字的值const currentNumber = Math.round(targetNumber * (progress / duration));counterElement.textContent = currentNumber; // 更新数字显示if (progress < duration) {// 继续下一帧动画requestAnimationFrame(step);//60FPS执行一次,延时器//60FPS = 一帧} else {// 动画结束,显示最终数字counterElement.textContent = targetNumber;}}// 启动动画requestAnimationFrame(step);</script>
</body>
</html>
Vue
以Vue3为例,Vue同理,使用的时候,只需要往封装的组件中传入目标数字即可
RollNumber.vue<template><!-- 数字滚动组件 --><div class="counter">{{ count }}</div>
</template>
<script setup>
import { onMounted } from "vue";
// const targetNumber = 100; // 指定的目标数字
const duration = 1200; // 动画持续时间,单位为毫秒
const count = ref(0); // 获取数字显示的元素
const props = defineProps(["targetNumber"]);
let startTime = null; // 动画开始时间
function step(timestamp) {if (!startTime) startTime = timestamp; // 记录动画开始时间const progress = timestamp - startTime; // 计算动画进度// 根据动画进度计算当前数字的值const currentNumber = Math.round(+props.targetNumber * (progress / duration));count.value = currentNumber; // 更新数字显示if (progress < duration) {// 继续下一帧动画requestAnimationFrame(step);} else {// 动画结束,显示最终数字count.value = props.targetNumber;}
}
onMounted(() => {requestAnimationFrame(step);
});
</script>
<style scoped lang="scss">
.counter {font-size: 24px;font-weight: 800;
}
</style>
<CommonRollNumber :targetNumber="2"></CommonRollNumber>