我有这个代码完美计算,但客户希望它从16.5到9.99。我确信可以使结束数字包含两个十进制数字。作为代码底部的选项,您会注意到有一个十进制选项。也许计算的中途我可以将它从1位小数改为2位小数点?我怎样才能做到这一点?谢谢!
(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: 1, // 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);
jQuery(function($) {
$('#heroCounter').countTo({
from: 16.5,
to: 9.9,
speed: 1500,
refreshInterval: 50,
onComplete: function(value) {
console.debug(this);
}
});
});
答案 0 :(得分:1)
如果我了解你应该添加decimals
选项:
$('#heroCounter').countTo({
from: 16.5,
to: 9.9,
speed: 1500,
decimals: 2,
refreshInterval: 50,
onComplete: function(value) {
console.debug(this);
}
});
或将$(_this).html(value.toFixed(options.decimals));
更改为$(_this).html(value.toFixed(2));
更新:@GuillermoGutiérrez - $(_this).html(value.toFixed(options.decimals, 2).toString().replace(/(\.[0-9]*?)0+$/, "$1"));
答案 1 :(得分:0)
您想动态更改选项吗?如果是http://jsfiddle.net/tarabyte/82qBL/3/
添加对选项get / set
的支持$.fn.countTo = function(options) {
if(typeof options === 'string') {
var name = arguments[0],
value = arguments[1];
if(typeof value === 'undefined') { //getter
var data = this.eq(0).data('countTo');
return data && data[name];
}
return this.each(function(){ //setter
var data = $(this).data('countTo');
data && (data[name] = value);
});
}
// merge the default plugin settings with the custom options
options = $.extend({}, $.fn.countTo.defaults, options || {});
...
$(this).data('countTo', options); //store current options in element's data
更改选项onUpdate
$('#heroCounter').countTo({
from: 16.5,
to: 7.11,
speed: 2900,
decimals: 1,
refreshInterval: 50,
onUpdate: function(value){
console.log($(this).countTo('from')); //get prop
if(value < 10) {
$(this).countTo('decimals', 2); //set prop
}
},
onComplete: function(value) {
console.debug(this);
}
});