如何使用Jquery为数字添加动画效果

dps*_*dce 9 jquery jquery-plugins jquery-animate

我试图动画说233美元到250美元或从250减少到233,我不想用230替换233而不是我想要一种反击效果,并且在滚动数字时也需要缩放效果.我是Jquery的新手,任何帮助都将受到高度赞赏.

Mat*_*all 18

HTML

<button id="start">Start</button>
<button id="reset">Reset</button>
<input id="counter" value="233"/>
Run Code Online (Sandbox Code Playgroud)

JavaScript的

$(function ()
{
    var $start = $('#start'),
        start = $start.get(0),
        $reset = $('#reset'),
        reset = $reset.get(0),
        $counter = $('#counter'),
        startVal = $counter.text(),
        currentVal = startVal,
        endVal = 250,
        prefix = '$',
        fontSize = $counter.css('font-size');

    $start.click(function ()
    {
        this.disabled = true;
        var i = setInterval(function ()
        {
            if (currentVal === endVal)
            {
                clearInterval(i);
                reset.disabled = false;
                $counter.animate({fontSize: fontSize});
            }
            else
            {
                currentVal++;
                $counter.text(prefix+currentVal).animate({fontSize: '+=1'}, 100);
            }
        }, 100);
    });

    $reset.click(function ()
    {
        $counter.text(prefix + startVal);
        this.disabled = true;
        start.disabled = false;
    }).click();
});
Run Code Online (Sandbox Code Playgroud)

演示→

  • 如果您了解此代码,则扩展它以满足您的需求应该非常简单.既然你是jQuery的新手,我会说这将是一个很好的学习练习.试试看. (7认同)

The*_* Oz 13

谷歌搜索这个片段,它看起来非常棒和紧凑:

// Animate the element's value from 0% to 110%:
jQuery({someValue: 0}).animate({someValue: 110}, {
    duration: 1000,
    easing:'swing', // can be anything
    step: function() { // called on every step
        // Update the element's text with rounded-up value:
        $('#el').text(Math.ceil(this.someValue) + "%");
    }
});
Run Code Online (Sandbox Code Playgroud)

小提琴