我试图找出是否有人知道一个已经存在的jQuery插件,它将以指定的速度增加到目标数量.
I'm trying to find out if anyone knows about an already existing jQuery plugin that will count up to a target number at a specified speed.
例如,在 Gmail主页的标题为"很多空间".它在<span>标记中有一个起始编号,然后每秒逐渐递增计数.
For example, take a look at Google's number of MB of free storage on the Gmail homepage, under the heading that reads "Lots of space". It has a starting number in a <span> tag, and slowly counts upward every second.
我正在寻找类似的东西,但我希望能够指定:
I'm looking for something similar, but I'd like to be able to specify:
- 起始号码
- 结束号码
- 从头到尾需要花费的时间.
- 一个自定义的回调函数,可以在计数器完成时执行.
我最终创建了自己的插件.在这种情况下,这可以帮助任何人:
I ended up creating my own plugin. Here it is in case this helps anyone:
(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);以下是一些使用示例代码:
Here's some sample code of how to use it:
<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上查看演示: jsfiddle/YWn9t/
View the demo on JSFiddle: jsfiddle/YWn9t/
更多推荐
jQuery计数器最多可计算一个目标数
发布评论