jQuery Count Numbers Up

时间:2013-05-09 17:26:32

标签: jquery animation

我对javascript并不擅长,但我希望有一个很好的小动画,它可以向上计数。我在Github上找到了this,但它的速度很慢。 (我正在计算一个10位小数)。任何人都有关于如何修改它的任何提示,所以它更快? (我试图减少数据间隔,但它停滞在“0”。

<p class="counter" data-interval="0" data-format="999999" data-stop="193847"></p>

6 个答案:

答案 0 :(得分:5)

我找到了完美的解决方案:

https://github.com/mhuggins/jquery-countTo

答案 1 :(得分:3)

让我们说你想在5秒内计算到200,000。

这将是每秒40,000个增量或60,000个60,000毫秒,这将是每次迭代1.5 ms的间隔。

您使用的任何浏览器很可能无法处理这种间隔。执行此操作的最佳方法可能是确定您希望它计算到最终值的速度,并更改步骤,以便在给定更合理的间隔的情况下以正确的时间到达目的地。

例如,假设5000ms是您想要它需要多长时间,并且您希望您的间隔为20ms。

鉴于您有5000/20或250步。您需要计算200000/250或800才能在5秒内达到结束值。

答案 2 :(得分:2)

这对您也很简单,您可以通过更改计数器:0 通过更改持续时间来改变速度和更改起始数 p>

$('.count').each(function () {
  var $this = $(this);
  jQuery({ Counter: 0 }).animate({ Counter: $this.attr('data-stop') }, {
    duration: 1000,
    easing: 'swing',
    step: function (now) {
      $this.text(Math.ceil(now));
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="count" data-stop="193847">193847</span>
<br/>
<span class="count" data-stop="190">190</span>
<br/>
<span class="count" data-stop="1938">1938</span>

答案 3 :(得分:1)

您不需要jQuery插件,只需使用.animate:

jQuery('.counter').each(function(){
  var $elm = this;
  var from = {property: 0};
  var to = {property: $elm.data('stop')};
  var duration = $elm.data('duration');

  jQuery(from).animate(to, {
      duration: duration,
      step: function() {
          $elm.html(this.property);
      }
  });
});

提示:您可以通过设置jQuery.fx.interval来优化jQuery的帧速率,默认情况下它是13(ms)。

更多示例:http://james.padolsey.com/javascript/fun-with-jquerys-animate/

答案 4 :(得分:0)

从您发布的插件中,似乎有一个名为 interval 的选项。默认值为1000毫秒,尝试减​​少它以使其计数更快。

这样的事情可以解决问题:

<span></span>

<script>
$('span').addClass('counter counter-analog')
         .counter({
   // several options here
    interval: 1,
    });

</script>

希望它有所帮助!

答案 5 :(得分:0)

如果有人想以一定的增量增加计数器,请使用

// HTML

<span class="stat-count">10000</span>

// JS

$(function() {
    function count($this){
        var current = parseInt($this.html(), 10);
        current = current + 50; /* Where 50 is increment */

    $this.html(++current);
    if(current > $this.data('count')){
        $this.html($this.data('count'));
    } else {    
        setTimeout(function(){count($this)}, 5);
    }
}        

$(".stat-count").each(function() {
  $(this).data('count', parseInt($(this).html(), 10));
  $(this).html('0');
  count($(this));
 });

});

页面加载时的Jquery计数数字具有一定的限制,计数时间和计数增量。