jQuery计数器计数到目标数字

我试图找出是否有人知道一个已经存在的jQuery插件,将以指定的速度达到目标数量。

例如,在Gmail主页上的“大量空间”标题下,查看Google的免费存储空间数量。 它在一个<span>标签中有一个起始号码,并且每秒都慢慢向上计数。

我正在寻找类似的东西,但我想能够指定:

  • 起始号码
  • 结束号码
  • 从开始到结束应该花费的时间。
  • 计数器完成时可以执行的自定义callback函数。

我结束了创build我自己的插件。 在这种情况下,这有助于任何人:

 (function($) { $.fn.countTo = function(options) { // merge the default plugin settings with the custom options options = $.extend({}, $.fn.countTo.defaults, options || {}); // how many times to update the value, and how much to increment the value on each update var loops = Math.ceil(options.speed / options.refreshInterval), increment = (options.to - options.from) / loops; return $(this).each(function() { var _this = this, loopCount = 0, value = options.from, interval = setInterval(updateTimer, options.refreshInterval); function updateTimer() { value += increment; loopCount++; $(_this).html(value.toFixed(options.decimals)); if (typeof(options.onUpdate) == 'function') { options.onUpdate.call(_this, value); } if (loopCount >= loops) { clearInterval(interval); value = options.to; if (typeof(options.onComplete) == 'function') { options.onComplete.call(_this, value); } } } }); }; $.fn.countTo.defaults = { from: 0, // the number the element should start at to: 100, // the number the element should end at speed: 1000, // how long it should take to count between the target numbers refreshInterval: 100, // how often the element should be updated decimals: 0, // the number of decimal places to show onUpdate: null, // callback method for every time the element is updated, onComplete: null, // callback method for when the element finishes updating }; })(jQuery); 

以下是如何使用它的一些示例代码:

 <script type="text/javascript"><!-- jQuery(function($) { $('.timer').countTo({ from: 50, to: 2500, speed: 1000, refreshInterval: 50, onComplete: function(value) { console.debug(this); } }); }); //--></script> <span class="timer"></span> 

在JSFiddle上查看演示: http : //jsfiddle.net/YWn9t/

你可以使用jQuery的animationfunction

 // Enter num from and to $({countNum: 99}).animate({countNum: 1000}, { duration: 8000, easing:'linear', step: function() { // What todo on every count console.log(Math.floor(this.countNum)); }, complete: function() { console.log('finished'); } }); 

http://jsbin.com/upazas/958/

我已经创build了最小的代码来做到这一点。 这不仅是计算,而且还包括任何需要在特定时间运行的任务。 (比方说,做5秒):

  • 演示页面

  • Github项目

演示代码:

 var step = function(t, elapsed){ // easing t = t*t*t; // calculate new value var value = 300 * t; // will count from 0 to 300 // limit value ("t" might be higher than "1") if( t > 0.999 ) value = 300; // print value (converts it to an integer) someElement.innerHTML = value|0; }; var done = function(){ console.log('done counting!'); }; // Do-in settings object var settings = { step : step, duration : 3, done : done, fps : 24 // optional. Default is requestAnimationFrame }; // initialize "Do-in" instance var doin = new Doin(settings); 

不知道插件,但这不应该太难:

 ;(function($) { $.fn.counter = function(options) { // Set default values var defaults = { start: 0, end: 10, time: 10, step: 1000, callback: function() { } } var options = $.extend(defaults, options); // The actual function that does the counting var counterFunc = function(el, increment, end, step) { var value = parseInt(el.html(), 10) + increment; if(value >= end) { el.html(Math.round(end)); options.callback(); } else { el.html(Math.round(value)); setTimeout(counterFunc, step, el, increment, end, step); } } // Set initial value $(this).html(Math.round(options.start)); // Calculate the increment on each step var increment = (options.end - options.start) / ((1000 / options.step) * options.time); // Call the counter function in a closure to avoid conflicts (function(e, i, o, s) { setTimeout(counterFunc, s, e, i, o, s); })($(this), increment, options.end, options.step); } })(jQuery); 

用法:

 $('#foo').counter({ start: 1000, end: 4500, time: 8, step: 500, callback: function() { alert("I'm done!"); } }); 

例:

http://www.ulmanen.fi/stuff/counter.php

我想这个用法是不言自明的。 在这个例子中,计数器将从1000开始,每隔500ms计数8次,计数结束后会调用callback函数。

我不知道任何现有的插件,但使用JavaScript定时事件自己编写一个插件似乎相当容易。

一种不同的方法。 使用Tween.js作为计数器。 它让柜台放慢速度,加速,反弹,以及其他一些好东西,随着柜台到达的地方。

http://jsbin.com/ekohep/2/edit#javascript,html,live

请享用 :)

PS,不使用jQuery – 但显然可以。

尝试jCounter ,它有一个customRange设置,你可以在其中指定开始和结束的号码,它可以包括最后的回退你想要的。

需要rest一下,所以我拼凑在一起。 不知道这是值得创build一个插件虽然。

 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title> Counter </title> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.js"></script> <script type="text/javascript"> //<![CDATA[ function createCounter(elementId,start,end,totalTime,callback) { var jTarget=jQuery("#"+elementId); var interval=totalTime/(end-start); var intervalId; var current=start; var f=function(){ jTarget.text(current); if(current==end) { clearInterval(intervalId); if(callback) { callback(); } } ++current; } intervalId=setInterval(f,interval); f(); } jQuery(document).ready(function(){ createCounter("counterTarget",0,20,5000,function(){ alert("finished") }) }) //]]> </script> </head> <body> <div id="counterTarget"></div> </body> </html> 

另一种不使用jQuery的方法是使用Greensock的TweenLite JS库。

演示http://codepen.io/anon/pen/yNWwEJ

 var display = document.getElementById("display"); var number = {param:0}; var duration = 1; function count() { TweenLite.to(number, duration, {param:"+=20", roundProps:"param", onUpdate:update, onComplete:complete, ease:Linear.easeNone}); } function update() { display.innerHTML = number.param; } function complete() { //alert("Complete"); } count();