Non-linear “animation” of numeric value with JavaS

2019-01-28 09:09发布

I want to make an animation like this one in Google Analytics on active users.

Analytics counter


I saw some scripts that do the animation, but they do it in linear mode, like, the speed is the same from 0 to XXX, I want it to start slowly, gain speed, and finish slowly again.

How would I do this in javascript/jquery?


As requested, what I tried:

<span id="counter">0</span>    

$(function ()
{
    var $counter = $('#counter'),
        startVal = $counter.text(),
        currentVal,
        endVal = 250;


    currentVal = startVal;
    var i = setInterval(function ()
    {
        if (currentVal === endVal)
        {
            clearInterval(i);
        }
        else
        {
            currentVal++;
            $counter.text(currentVal);
        }
    }, 100);


});

But I don't think it's the way to go...

1条回答
Summer. ? 凉城
2楼-- · 2019-01-28 09:44

I would use jQuery's built-in animation for this.

If you pass a function to the step option for .animate(), it will be fired for each tick during animation. That way, jQuery will handle all of the easing and what not for you. You just need to handle the data.

$({countValue:0}).animate(
    {countValue:346},
    {
        duration: 5000, /* time for animation in milliseconds */
        step: function (value) { /* fired every "frame" */
            console.log(value);
        }
    }
);

In the console, you will see values between 0 and 346, complete with easing.

查看更多
登录 后发表回答