JS 自定義實現數字滾動處理
阿新 • • 發佈:2021-02-04
技術標籤:jQuery外掛JS 自定義實現數字滾動處理javascriptjquery
一、瀏覽器端js自定義實現數字滾動
使用示例:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script src="../src/qlCountUp.js"></script> <style> #num { font-weight: bold; color: red; } </style> </head> <body> <div id="num"></div> <div id="num2"></div> <script> var timeStart, timeEnd; new qlCountUp({ el: '#num', count: 111, onStart: function () { timeStart = new Date(); }, onEnd: function () { timeEnd = new Date(); var span = timeEnd - timeStart; //秒鐘 console.info(span / 1000); } }); new qlCountUp({ el: '#num2', count: 99999 }); </script> </body> </html>
coungup.js 原始碼:
/** * 計數器封裝 * 特點:滾動顯示數字展示,固定展示間隔,滾動時間隨著數字增大而增加 * el:'',---頁面元素選擇器 * count:1000--展示的數字大小 * speed:20 ---展示單位數字的毫秒數 * onStart:function----滾動開始事件 * onEnd:function ---滾動結束事件 */ (function (win, doc) { var defaultOptions = { el: '',//當前展示的元件的篩選器 count: 1000, speed: 10, onStart: function () { }, onEnd: function () { } } function countUp(options) { var _this = this; if (!options) throw new Error("請配置計算引數"); _this = Object.assign(_this, defaultOptions, options); _this.element = doc.querySelector(_this.el) || doc.querySelectorAll(_this.el); if (!_this.element) throw new Error("獲取dom元素失敗"); //計算處理 _this.countAdd(); } countUp.prototype = { //按指定速度計算並展示 countAdd: function () { var _this = this; //初始化單位數字 var element = _this.element; var max = 100, //最大步數 count = _this["count"], speed = Math.floor(count / max), sum = 0,//計算累計總和 running = 1; //滾動開始 _this.onStart(); var timer = setInterval(() => { if (running <= max && speed != 0) { sum = speed * running; element.innerText = sum; running++; } else if (sum < count) { sum++; element.innerText = sum; } else { clearInterval(timer); //滾動結束 _this.onEnd(); } }, _this.speed); } } win.qlCountUp = countUp; })(window, document);
展示效果:
二、小程式端js自定義實現數字滾動
展示效果如下:
小程式端程式碼沒有公開,如果需要程式碼或者演示示例的技術,點選找客服領取。
更多: