我试图找出是否有人知道已经存在的jQuery插件将以指定的速度计算到目标数量。
例如,请查看Google在Gmail homepage上的空闲存储空间数量,标题为“空间很大”。它的起始编号为<span>
标记,并且每秒慢慢向上计数。
我正在寻找类似的东西,但我希望能够指明:
答案 0 :(得分:134)
我最终创建了自己的插件。这是为了以防万一:
(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/
答案 1 :(得分:71)
您可以使用jQuery animate功能
// 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');
}
});
答案 2 :(得分:12)
我已经创建了最简单的代码。它不仅适用于计数,也适用于需要在给定时间内运行的任何任务。 (比方说,做5秒钟的事情):
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);
答案 3 :(得分:8)
不知道插件,但这不应该太难:
;(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!");
}
});
示例:
我猜这种用法是不言自明的;在这个例子中,计数器将从1000开始,并以500毫秒的间隔在8秒内计数到4500,并在计数完成时调用回调函数。
答案 4 :(得分:2)
我不知道任何现有的插件,但使用JavaScript Timing Events自己编写插件似乎相当容易。
答案 5 :(得分:2)
一种不同的方法。将Tween.js用于计数器。它允许计数器减速,加速,弹跳,以及一系列其他好东西,因为计数器到达它的位置。
http://jsbin.com/ekohep/2/edit#javascript,html,live
享受:)
PS,不使用jQuery - 但显然可以。
答案 6 :(得分:1)
尝试jCounter,它有一个customRange设置,您可以在其中指定开始和结束编号,它也可以计算,包括最后想要的后备。
答案 7 :(得分:0)
需要休息一下,所以我一起拼凑了以下内容。不确定是否值得创建一个插件。
<!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>
答案 8 :(得分:0)
没有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();
答案 9 :(得分:0)
CodePen Working Example
有关更多GitHub repo
# convert
dd[, "first"] = as.integer(dd[, "first"])
# apply now works
apply(dd, 1, function(x) x["first"] == x[7])
# 1 2 3
# FALSE TRUE NA
# but isn't this easier?
dd[, "first"] == dd[, "six"]
# [1] FALSE TRUE NA
答案 10 :(得分:-1)
您可以为此使用jani动画功能。
$({ countNum: $('.code').html() }).animate({ countNum: 4000 }, {
duration: 8000,
easing: 'linear',
step: function () {
$('.code').html(Math.floor(this.countNum) );
},
complete: function () {
$('.code').html(this.countNum);
//alert('finished');
}
});
这是原始文章 http://mishelshaji.co.in/2018/animated-number-counter-using-jquery/