jQuery计数器最多可计算一个目标数

编程入门 行业动态 更新时间:2024-10-11 01:10:53
本文介绍了jQuery计数器最多可计算一个目标数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我试图找出是否有人知道一个已经存在的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计数器最多可计算一个目标数

本文发布于:2023-10-18 15:37:10,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1504652.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:最多   计数器   目标   可计算   jQuery

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!