1. 程式人生 > 程式設計 >JavaScript實現餘額數字滾動效果

JavaScript實現餘額數字滾動效果

目錄
  • 1.實現背景
  • 2.實現思路
  • 3.實現過程

1.實現背景

上週在一個完成任務領取紅包的活動需求中,需要實現一個使用者點選按鈕彈出領取紅包彈窗後,在關 閉彈窗返回原來的頁面時,頁面餘額數字部分要展示一個每一位數字滾動後www.cppcns.com的效果。
因為之前沒做過這樣的效果,一開始也不知道要如何實現,本來想在上找一下相關的庫,看到一個最高star的庫,但發現它是依賴的,而且不可以npm包引入。感覺就很沒有必要,本來專案是react框架的,就是要儘量少的操作DOM,為了解決這個滾動就要引入jQuery,感覺不太合適。所以我決定還是自己實現,先看了一下別人的思路,然後自己再去實現。

2.實現思路

其實就是將傳入的帶滾動的n位數字拆分成每一個要滾動的數,然後動態的建立裝著滾動到每一位相應數字的容器,然後放入傳入的目標容器中。滾動到每一位相應的數字的實現可以通過動態建立從0到相應數字的間隔數的div,div的內容分別為對應的數字,就像一個豎直寫著從0-n的長紙條,然後拉著它在指定時間內從0上拉到目標數字。

3.實現過程

既然要封裝,還是寫成class的形式吧,話不多說,直接上程式碼吧

/**
 * 實現數字滾動的效果的類
 */
class DigitScroll {
  constructor(options) {
    //獲取容器的DOM,沒有則丟擲錯誤
    this.container = document.querySelector(options.container);
    if (!this.container) {
      throw Error("no container");
    }
    this.container.style.overflow = "hidden";
    this.container.style.display = "flex";
    //可視容器高度 也是滾動間隔距離,容器要設定高度,否則預設30px
    this.rollHeight = parseInt(getComputedStyle(this.container).height) || 30;
    this.container.style.height = this.rollHeight + "px";
  }
  roll(num) {
    // 將傳入的要滾動的數字拆分後初始化每一位數字的容器
    this.initDigitEle(num);
    const numEles = this.container.querySelectorAll(".single-num");
    // 遍歷生成每一位數字的滾VIOsaioxGV
動佇列,如滾動到7,則生成內容為0,1,2,3,4,5,6,7的7個div,用於滾動動畫 [...numEles].forEach((numEle,index) => { const curNum = 0; let targetNum = Number(this.numberArr[index]); if (curNum >= targetNum) { targetNum = targetNum + 10; } let cirNum = curNum; // 文件碎片,拼湊好後一次性插入節點中 const fragment = document.createDocumentFragment(); // 生成從0到目標數字對應的div while (targetNum >= cirNum) { const ele = document.createElement("div"); ele.innerHTML = cirNum % 10; cirNum++; fragment.appendChild(ele); www.cppcns.com
} numEle.innerHTML = ""; numEle.appendChild(fragment); //重置位置 numEle.style.Text += "-webkit-transition-duration:0s;-webkit-transform:translateY(0)"; setTimeout(() => { numEle.style.cssText += `-webkit-transition-duration:1s;-webkit-transform:translateY(${ -(targetNum - curNum) * this.rollHeight }px);`; },50); }); } // 初始化容器 initDigitEle(num) { // 數字拆分位數 const numArr = num.toString().split(""); // 文件碎片,拼湊好後一次性插入節點中 const fragment = document.createDocumentFragment(); numArr.forEach((item) => { const el = document.createElement("div"); // 數字是要滾動的,非數字如.是不滾動的 if (/[0-9]/.test(item)) { el.className = "single-num"; el.style.height = this.rollHeight + "px"; el.style.lineHeight = this.rollHeight + "px"; } else { el.innerHTML = item; el.className = "no-move"; el.style.verticalAlign = "bottom"; } // el.style.float='left'; fragment.appendChild(el); },[]); this.container.innerHTML = ""; this.container.appendChild(fragment); // 儲存滾動的數字 this.numberArr = numArr.filter((item) => /[0-9]/.test(item)); } }

到此這篇關於實現餘額數字滾動效果的文章就介紹到這了,更多相關Script實現 數字滾動 內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!