前言
数字从0.00滚动到某个数值的动画
实现(React版本)
Dom
<div className="number" ref={numberRef}>0.00</div>
JS
const _initNumber = () => {const targetNumber = 15454547.69;const duration = 1500;const numberElement = numberRef.current;if(!numberElement)returnlet startTime = null;function formatNumber(num) {return num.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 });}function animateNumber(timestamp) {if (!startTime) startTime = timestamp;const progress = timestamp - startTime;const currentNumber = Math.min(progress / duration * targetNumber, targetNumber);const currentFormattedNumber = formatNumber(currentNumber);const totalLength = formatNumber(targetNumber).length;const currentLength = Math.floor(progress / duration * totalLength);const displayNumber = currentFormattedNumber.slice(0, currentLength);numberElement.textContent = displayNumber;if (progress < duration) {requestAnimationFrame(animateNumber);} else {numberElement.textContent = formatNumber(targetNumber);}}requestAnimationFrame(animateNumber);}
效果
最后
通过requestAnimationFrame去实现动画效果,toLocaleString做整数数值三位分割~