2013-05-09 68 views
1

我對JavaScript沒有任何好處,但我很想擁有一個向上計數的漂亮的小動畫。我在Github上發現了this,但它的速度很慢。 (我正在計算一個有10位小數的數字)。任何人有關於如何修改它的任何提示,所以它更快? (我試圖降低數據間隔,但它在「0」之類的停滯。jQuery Count Numbers Up

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

請張貼代碼你在這裏試過。 – j08691 2013-05-09 17:28:09

+0

該頁面上的第二個例子似乎算得非常快。複製它並添加更多數字。 – Barmar 2013-05-09 17:29:47

+0

我試過了, - 不起作用。 – Mats 2013-05-09 17:32:03

回答

0

從您發佈的插件,似乎有一種選擇叫間隔,默認爲1000毫秒,所以嘗試它計算速度更快減少它

類似的東西應該做的伎倆:

<span></span> 

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

</script> 

希望它可以幫助

+0

試過了。仍然很慢.. – Mats 2013-05-09 17:34:03

3

讓!假設你想在5秒內計數到20萬。

這將是每秒40,000增量或60,000毫秒40,000,這將是每次迭代1.5毫秒的時間間隔。

很可能您使用的任何瀏覽器都無法處理這種間隔。做到這一點的最佳方法可能會決定你希望它的數量達到最終值的多少,並改變步驟,以便在給定更爲理智的時間間隔的情況下,以正確的時間量到達目的地。

例如,5000毫秒是你想要的時間,你希望你的間隔是20ms。

假設您有5000/20或250步。你將不得不以200000/250或800來計數,以在5秒內達到你的結局值。

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 jQuery的幀率.fx.interval,默認情況下是13(ms)。

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

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在頁面加載時計數一定的限制,計算時間和計數增量。

1

這將幫助你簡單過,你可以變化速度通過改變時間變化通過改變計數器起始號碼:0

$('.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>