JS控制數字從指定數開始變化


// 引用基本的jquery.js
<!-- 數字變化 --> <div class="list1"> <div class="content f-cb"> <div> <p class="p1 timer" data-to="2006" data-speed="1500">2006</p> <p class="p2">06年開始“小組合作學習”研究</p> </div> <span></span> <div> <p class="p1 timer" data-to="2011" data-speed="1500">2011</p> <p class="p2">1年成立教育課改中心</p> </div> <span></span> <div> <p class="p1 timer" data-to="57" data-speed="1500">57</p> <p class="p2">目前已經有57所實驗學校</p> </div> <span></span> <div> <p class="p1 timer" data-to="506" data-speed="1500">506</p> <p class="p2">506家課改聯盟學校</p> </div> </div> </div> <script type="text/javascript"> var istrue = true; $(window).on("scroll", function() { var s = $(window).scrollTop(); $(".timer").each(count); function count(a) { var b = $(this); a = $.extend({}, a || {}, b.data("countToOptions") || {}); b.countTo(a) }; istrue = false; $(".timer").removeClass("timer") }) //設置計數 $.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); } </script>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM