You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

jQuery数字增长动画:实现x秒后快转慢调速效果求助

实现数字增长动画的“先快后慢”效果

你的代码问题在于:jQuery的.animate()方法一旦启动,就会使用初始化时传入的duration参数,后续修改speed变量根本不会影响正在运行的动画——相当于动画的时长在一开始就被“固定”了,所以你设置的setTimeout改speed完全没起作用。

要实现“前2秒快速增长,之后变慢直到结束”的效果,我们可以把动画拆成两个阶段来处理,下面是两种可行的方案:

方案1:定时器+animate组合(简单直观)

先通过定时器快速跑2秒的增长,之后切换到jQuery的animate来完成剩余部分,总时长保持你原来的15000ms:

$('.holder').each(function() {
    const $element = $(this);
    const target = $element.data('number');
    let current = 0;
    
    // 第一阶段:前2秒快速增长,这里设置前2秒完成70%的目标值(可自行调整)
    const fastDuration = 2000;
    const fastStep = target * 0.7 / (fastDuration / 16); // 按浏览器16ms一帧计算步长
    const fastTimer = setInterval(() => {
        current += fastStep;
        if (current >= target * 0.7) {
            clearInterval(fastTimer);
            // 第二阶段:慢速完成剩下的30%,用时13000ms(总时长15000-2000)
            $element.prop('Counter', current).animate({ Counter: target }, {
                duration: 13000,
                easing: 'swing',
                step: function(now) {
                    $(this).text(Math.ceil(now).toLocaleString('en'));
                }
            });
        } else {
            $element.text(Math.ceil(current).toLocaleString('en'));
        }
    }, 16);
});

方案2:用requestAnimationFrame(更流畅)

利用浏览器原生的动画API,它会跟着浏览器刷新频率执行,动画更平滑:

$('.holder').each(function() {
    const $element = $(this);
    const target = $element.data('number');
    let current = 0;
    let startTimestamp = null;
    const fastPhaseTime = 2000; // 快速阶段时长
    const totalTime = 15000; // 总动画时长

    function updateCount(timestamp) {
        if (!startTimestamp) startTimestamp = timestamp;
        const elapsed = timestamp - startTimestamp;

        if (elapsed < fastPhaseTime) {
            // 快速阶段:按比例增长到目标的70%
            const progress = elapsed / fastPhaseTime;
            current = target * 0.7 * progress;
            $element.text(Math.ceil(current).toLocaleString('en'));
            requestAnimationFrame(updateCount);
        } else if (current < target) {
            // 慢速阶段:用animate完成剩余部分
            const remainingTime = totalTime - fastPhaseTime;
            $element.prop('Counter', current).animate({ Counter: target }, {
                duration: remainingTime,
                easing: 'swing',
                step: function(now) {
                    $(this).text(Math.ceil(now).toLocaleString('en'));
                }
            });
        }
    }

    requestAnimationFrame(updateCount);
});

注意点

  • 你可以调整快速阶段完成的目标比例(比如把0.7改成0.6),来控制快慢阶段的数值分配
  • 总时长保持和你原代码一致的15000ms,确保整体节奏符合预期

内容的提问来源于stack exchange,提问作者gampang.ngelu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 08:43:37