我试图找出是否有人知道一个已经存在的jQuery插件,将以指定的速度计数到目标数字。
例如,请查看Gmail homepage上Google的免费存储空间数量,在“大量空间”标题下。它的起始编号位于< span>标签,并且每秒慢慢向上计数。
我在寻找类似的东西,但我想能够指定:
解决方法
我最后创建自己的插件。这里是为了帮助任何人:
(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/