/** * 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:500, //设置步长的时间 refreshinterval:1, //隔间值 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() { //500 鏍规嵁鏁板瓧涓婇潰鐨勫唴瀹� 璁$畻楂樺害 婊氬埌姝ゅ尯鍩� 鏁板瓧寮€濮嬫粴鍔� //寮€濮嬫墍鏈夌殑璁℃椂鍣� $('.timer').each(count); $('.count-title').removeclass('timer'); }); function count(options) { var $this = $(this); options = $.extend({}, options || {}, $this.data('counttooptions') || {}); $this.countto(options); }