jQuery数字计数器

jQuery number counter

本文关键字:计数器 数字 jQuery      更新时间:2024-05-07

我正在使用这个jQuery片段来将数字计数器从0到span中提供的数字设置为动画。有人能告诉我如何修改它,使数字在给定值开始时向下计数为0吗?

<span class="count">200</span>
$('.count').each(function () {
    $(this).prop('Counter', 0).animate({
        Counter: $(this).text()
    }, {
        duration: 4000,
        easing: 'swing',
        step: function (now) {
            $(this).text(Math.ceil(now));
        }
    });
});

类似的东西?我假设step函数中的"now"只是在计算步数。

$('.count').each(function () {
    $(this).data('start', parseInt($(this).text())).animate({
        Counter: $(this).text()
    }, {
        duration: 4000,
        easing: 'swing',
        step: function (now) {
            $(this).text($(this).data(start) - now);
        }
    });
});

我在jsFiddle中验证了这一点(https://jsfiddle.net/0mtht3xm/):

$('.count').each(function () {
    $(this).data('start', parseInt($(this).text())).prop('Counter', 0).animate({
        Counter: $(this).text()
    }, {
        duration: 4000,
        easing: 'swing',
        step: function (now) {
            $(this).text($(this).data('start') - Math.ceil(now));
        }
    });
});

有无数种不同的方法可以创建倒计时到0的计数器。我就是这么做的:

HTML:

<span class="count">200</span>

JS:

var $count = $('.count');
var num = parseInt($count.text());
var interval = window.setInterval(updateTime, 1000);
function updateTime() {
  num--;
  $count.text(num.toString());
  if (num <= 0) {
    window.clearInterval(interval);
  }
}