Я пытаюсь узнать, знает ли кто-либо об уже существующем плагине jQuery, который рассчитает до целевого числа на указанной скорости.
Например, смотрите на число Google МБ бесплатного хранения на домашней странице Gmail, в соответствии с заголовком, который читает "Много пространства". Это имеет стартовое число в a тег, и медленно рассчитывает вверх каждую секунду.
Я ищу что-то подобное, но я хотел бы смочь указать:
В итоге я создал свой собственный плагин. Вот на случай, если это кому-то поможет:
(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/
Нужен был перерыв, поэтому я сколотил следующее. Не уверен, что стоит создавать плагин.
<!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>
Не разбираюсь в плагинах, но это не должно быть слишком сложно:
;(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 и считать до 4500 за 8 секунд с интервалом в 500 мс, и вызовет функцию обратного вызова, когда подсчет будет закончен.
Я не знаю о каких-либо существующих плагинах, но кажется, что довольно легко написать один самостоятельно, используя JavaScript Timing Events.