how to animate numbers using Jquery

后端 未结 8 747
时光取名叫无心
时光取名叫无心 2021-02-02 02:31

I am trying to animate a say $233 to $250 or decreasing from 250 to 233 ,i dont want to replace 233 by 250 instead i want a counter kind of effect and at the time of scrolling

相关标签:
8条回答
  • 2021-02-02 03:15

    Here's a fun way to do it with a sort of slot machine effect.

    Assuming this simple HTML:

    <span id="foo">123</span> <!--- number to change --->
    <a href="#" id="go">Go!</a> <!--- start the slot machine --->
    

    Then:

    var changeto = 456;
    
    function slotmachine(id) {
        var thisid = '#' + id;
        var $obj = $(thisid);
        $obj.css('opacity', '.3');
        var original = $obj.text();
    
        var spin = function() {
            return Math.floor(Math.random() * 10);
        };
    
        var spinning = setInterval(function() {
            $obj.text(function() {
                var result = '';
                for (var i = 0; i < original.length; i++) {
                    result += spin().toString();
                }
                return result;
            });
        }, 50);
    
        var done = setTimeout(function() {
            clearInterval(spinning);
            $obj.text(changeto).css('opacity', '1');
        }, 1000);
    }
    
    $('#go').click(function() {
        slotmachine('foo');
    });
    

    Having the digits "resolve" one by one, movie-codebreaking-style, is left as an exercise.

    Example: http://jsfiddle.net/redler/tkG2H/

    0 讨论(0)
  • 2021-02-02 03:18

    Googled this snippet and it looks pretty awesome and compact:

    // 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) + "%");
        }
    });
    

    Fiddle

    0 讨论(0)
提交回复
热议问题