/** * created by lizhenya on 2018/6/28. */ // 数字效果 $.fn.countto = function (options) { options = options || {}; return $(this).each(function () { // 设置当前元素的选项 var settings = $.extend({}, $.fn.countto.defaults, { from: $(this).data('from'), to: $(this).data('to'), speed: $(this).data('speed'), refreshinterval: $(this).data('refresh-interval'), decimals: $(this).data('decimals') }, options); // 多少次更新的值,以及每个更新的值增加多少 var loops = math.ceil(settings.speed / settings.refreshinterval), increment = (settings.to - settings.from) / loops; // references & variables that will change with each update var self = this, $self = $(this), loopcount = 0, value = settings.from, data = $self.data('countto') || {}; $self.data('countto', data); // 如果可以找到现有的间隔,请先清除 if (data.interval) { clearinterval(data.interval); } data.interval = setinterval(updatetimer, settings.refreshinterval); // 用起始值初始化元素 render(value); function updatetimer() { value += increment; loopcount++; render(value); if (typeof(settings.onupdate) == 'function') { settings.onupdate.call(self, value); } if (loopcount >= loops) { // 删除间隔 $self.removedata('countto'); clearinterval(data.interval); value = settings.to; if (typeof(settings.oncomplete) == 'function') { settings.oncomplete.call(self, value); } } } function render(value) { var formattedvalue = settings.formatter.call(self, value, settings); $self.html(formattedvalue); } }); }; $.fn.countto.defaults = { from: 0, // 元素开始的数字 to: 0, // 元素结束的数字 speed: 1, // 在目标号码之间计算多长时间 refreshinterval: 0.5, // 更新元素的频率 decimals: 0, // 要显示的小数位数 formatter: formatter, // 处理程序用于格式化渲染前的值 onupdate: null, // 每次元素更新时的回调方法 oncomplete: null // 元素完成更新时的回调方法 }; function formatter(value, settings) { return value.tofixed(settings.decimals); } // 自定义格式化示例 $('#count-number').data('', { formatter: function (value, options) { return value.tofixed(options.decimals).replace(/\b(?=(?:\d{3})+(?!\d))/g, ' '); } }); function count(options) { var $this = $(this); options = $.extend({}, options || {}, $this.data('counttooptions') || {}); $this.countto(options); }