jQuery animated number counter from zero to value

后端 未结 10 713
天涯浪人
天涯浪人 2020-11-28 04:00

I have created a script to animate a number from zero to it\'s value.

Working

jQuery

10条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-28 04:48

    this inside the step callback isn't the element but the object passed to animate()

    $('.Count').each(function (_, self) {
        jQuery({
            Counter: 0
        }).animate({
            Counter: $(self).text()
        }, {
            duration: 1000,
            easing: 'swing',
            step: function () {
                $(self).text(Math.ceil(this.Counter));
            }
        });
    });
    

    Another way to do this and keep the references to this would be

    $('.Count').each(function () {
        $(this).prop('Counter',0).animate({
            Counter: $(this).text()
        }, {
            duration: 1000,
            easing: 'swing',
            step: function (now) {
                $(this).text(Math.ceil(now));
            }
        });
    });
    

    FIDDLE

提交回复
热议问题