(function( $ ){ "use strict"; $.fn.countup = function( options ) { // defaults var settings = $.extend({ 'time': 2000, 'delay': 10 }, options); return this.each(function(){ // store the object var $this = $(this); var $settings = settings; var counterupper = function() { if(!$this.data('counterupto')) { $this.data('counterupto',$this.text()); } var time = parseint($this.data("counter-time")) > 0 ? parseint($this.data("counter-time")) : $settings.time; var delay = parseint($this.data("counter-delay")) > 0 ? parseint($this.data("counter-delay")) : $settings.delay; var divisions = time / delay; var num = $this.data('counterupto'); var nums = [num]; var iscomma = /[0-9]+,[0-9]+/.test(num); num = num.replace(/,/g, ''); var isint = /^[0-9]+$/.test(num); var isfloat = /^[0-9]+\.[0-9]+$/.test(num); var decimalplaces = isfloat ? (num.split('.')[1] || []).length : 0; // generate list of incremental numbers to display for (var i = divisions; i >= 1; i--) { // preserve as int if input was int var newnum = parseint(math.round(num / divisions * i)); // preserve float if input was float if (isfloat) { newnum = parsefloat(num / divisions * i).tofixed(decimalplaces); } // preserve commas if input had commas if (iscomma) { while (/(\d+)(\d{3})/.test(newnum.tostring())) { newnum = newnum.tostring().replace(/(\d+)(\d{3})/, '$1'+','+'$2'); } } nums.unshift(newnum); } $this.data('counterup-nums', nums); $this.text('0'); // updates the number until we're done var f = function() { if ($this.data('counterup-nums')) { //加个这个判断 $this.text($this.data('counterup-nums').shift()); if ($this.data('counterup-nums').length) { settimeout($this.data('counterup-func'),delay); } else { delete $this.data('counterup-nums'); $this.data('counterup-nums', null); $this.data('counterup-func', null); } } }; $this.data('counterup-func', f); // start the count up settimeout($this.data('counterup-func'),delay); }; // perform counts when the element gets into view $this.waypoint(counterupper, { offset: '100%', triggeronce: true }); }); }; })( jquery ); $(function () { $('.counter').countup({ delay: 10, time: 1000 }); })