//窗口显示才加载 var wraptop = $(".index_about_num dl").offset().top; //alert(wraptop); var istrue = true; $(window).on("scroll", function() { var s = $(window).scrolltop(); if (s > wraptop -1500 && istrue) { $(".timer").each(count); function count(a) { var b = $(this); a = $.extend({}, a || {}, b.data("counttooptions") || {}); b.countto(a) }; istrue = false; }; }) //设置计数 $.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; //更改应用和变量 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:1000, //设置步长的时间 refreshinterval:100, //隔间值 decimals:0, //显示小位数 formatter: formatter, //渲染之前格式化 onupdate:null, //每次更新前的回调方法 oncomplete:null //完成更新的回调方法 }; function formatter(value, settings){ return value.tofixed(settings.decimals); } //自定义格式 $('#count-number').data('counttooptions',{ formmatter:function(value, options){ return value.tofixed(options.decimals).replace(/\b(?=(?:\d{3})+(?!\d))/g, ','); } }); //定时器 $('.timer').each(count); function count(options){ var $this=$(this); options=$.extend({}, options||{}, $this.data('counttooptions')||{}); $this.countto(options); }