jquery.countUp.js 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. (function($) {
  2. $.fn.countTo = function(opts) {
  3. // 合并自定义的方法
  4. var options = $.extend({}, $.fn.countTo.defaults, opts);
  5. return $(this).each(function() {
  6. // 设置总更新次数从而得到每次累加的值
  7. var _this = this,
  8. originalData = $(this).text(),//初始值
  9. loops = Math.ceil(options.speed / options.refreshInterval),//总更新次数
  10. increment = ($(this).text() - options.from) / loops,//每次累加的值
  11. loopCount = 0,
  12. value = options.from,
  13. interval = setInterval(updateTimer, options.refreshInterval);
  14. //console.log(Number(originalData).toFixed(options.decimals));
  15. function updateTimer() {
  16. value += increment;
  17. loopCount++;
  18. var str=value.toFixed(options.decimals);
  19. //运算到此时的字符串总长度
  20. this.sizeNum=str.length;
  21. //运算到此时的小数点前的字符长度
  22. this.sizeNumBefore=this.sizeNum-options.decimals-1;
  23. //判断 此时的小数点前的字符串长度是否>=需要的字符串小数点前的长度
  24. if(this.sizeNumBefore>=options.beforeSize) {
  25. $(_this).html(str+options.lastSymbol);
  26. } else{
  27. //在<的时候 前面要补0 再显示
  28. this._str = Array(options.beforeSize-this.sizeNumBefore + 1).join('0') + str;
  29. $(_this).html(this._str+options.lastSymbol);
  30. }
  31. if (typeof(options.onUpdate) == 'function') {
  32. options.onUpdate.call(_this, value, loopCount);
  33. //用call方法 把 options.onUndate=='function'(是一个方法), 替换掉_this,并把value作为和这个函数的参数
  34. }
  35. if (loopCount >= loops) {//over
  36. clearInterval(interval);
  37. $(_this).html(originalData+options.lastSymbol);
  38. value = $(_this).text();
  39. if (typeof(options.onComplete) == 'function') {
  40. //options.onComplete.call(_this, value, loopCount);
  41. options.onComplete(value,loopCount,_this);
  42. }
  43. }
  44. }
  45. });
  46. };
  47. $.fn.countTo.defaults = {
  48. lastSymbol:"%", //显示在最后的字符
  49. from: 0, // 开始时的数字
  50. speed: 1000, // 总时间
  51. refreshInterval: 100, // 刷新一次的时间
  52. beforeSize:0, //小数点前最小显示位数,不足的话用0代替
  53. decimals: 0, // 小数点后的位数
  54. onUpdate: null, // 更新时回调函数
  55. onComplete: null // 结束后回调函数
  56. };
  57. })(jQuery);