gpt4 book ai didi

jQuery 计数器计数到目标数字

转载 作者:行者123 更新时间:2023-12-03 21:27:07 25 4
gpt4 key购买 nike

我试图找出是否有人知道现有的 jQuery 插件,该插件将以指定的速度计数到目标数字。

例如,查看 Gmail homepage 上 Google 的免费存储空间 MB 数,在“大量空间”标题下。它的起始编号为 <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/

关于jQuery 计数器计数到目标数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2540277/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com