(function($) { $.fn.countto = function(opts) { // 合并自定义的方法 var options = $.extend({}, $.fn.countto.defaults, opts); return $(this).each(function() { // 设置总更新次数从而得到每次累加的值 var _this = this, originaldata = $(this).text(),//初始值 loops = math.ceil(options.speed / options.refreshinterval),//总更新次数 increment = ($(this).text() - options.from) / loops,//每次累加的值 loopcount = 0, value = options.from, interval = setinterval(updatetimer, options.refreshinterval); //console.log(number(originaldata).tofixed(options.decimals)); function updatetimer() { value += increment; loopcount++; var str=value.tofixed(options.decimals); //运算到此时的字符串总长度 this.sizenum=str.length; //运算到此时的小数点前的字符长度 this.sizenumbefore=this.sizenum-options.decimals-1; //判断 此时的小数点前的字符串长度是否>=需要的字符串小数点前的长度 if(this.sizenumbefore>=options.beforesize) { $(_this).html(str+options.lastsymbol); } else{ //在<的时候 前面要补0 再显示 this._str = array(options.beforesize-this.sizenumbefore + 1).join('0') + str; $(_this).html(this._str+options.lastsymbol); } if (typeof(options.onupdate) == 'function') { options.onupdate.call(_this, value, loopcount); //用call方法 把 options.onundate=='function'(是一个方法), 替换掉_this,并把value作为和这个函数的参数 } if (loopcount >= loops) {//over clearinterval(interval); $(_this).html(originaldata+options.lastsymbol); value = $(_this).text(); if (typeof(options.oncomplete) == 'function') { //options.oncomplete.call(_this, value, loopcount); options.oncomplete(value,loopcount,_this); } } } }); }; $.fn.countto.defaults = { lastsymbol:"%", //显示在最后的字符 from: 0, // 开始时的数字 speed: 1000, // 总时间 refreshinterval: 100, // 刷新一次的时间 beforesize:0, //小数点前最小显示位数,不足的话用0代替 decimals: 0, // 小数点后的位数 onupdate: null, // 更新时回调函数 oncomplete: null // 结束后回调函数 }; })(jquery);