数字滚动动画~

前言

数字从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)return
    let 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做整数数值三位分割~

相关推荐

  1. android recyclerview 中的animation滚动动画停止了?

    2024-07-10 22:28:04       33 阅读

最近更新

  1. 新媒体运营如何找准账号定位?

    2024-07-10 22:28:04       0 阅读
  2. C++--fill

    2024-07-10 22:28:04       0 阅读
  3. Docker部署kafka,Docker所在宿主机以外主机访问

    2024-07-10 22:28:04       0 阅读
  4. Rust编程-类面向对象编程

    2024-07-10 22:28:04       0 阅读
  5. 运筹学:决策优化的艺术

    2024-07-10 22:28:04       0 阅读
  6. OpenCV车牌识别技术详解

    2024-07-10 22:28:04       0 阅读

热门阅读

  1. H5小游戏开发,广告游戏开发制作

    2024-07-10 22:28:04       6 阅读
  2. 电脑多开卡顿的所有原因汇总

    2024-07-10 22:28:04       11 阅读
  3. 【C语言】通过fgets和fscanf了解读写文件流的概念

    2024-07-10 22:28:04       7 阅读
  4. mac上修改jupyterlab工作目录

    2024-07-10 22:28:04       7 阅读
  5. mongoexport导出聚合查询的mongo数据

    2024-07-10 22:28:04       5 阅读