微信小程序數字累加動態效果完善


問題描述:最近做了個關於記事的微信小程序,結果因為是個人主體,沒給審核通過,看來還是自己用吧。。。里面涉及到了一個數字累加的效果實現,百度到了一篇 http://www.wxapp-union.com/thread-1694-2-1.html,挺好使,有個問題就是如果是整數,並且數字不是很大的情況下,會中間過程一直是0,然后最后時候直接變成最終數字,沒有了中間過程。

解決辦法:看了看js,增加了一個固定的累加值取整,而不是繼續在原來已經有誤差(多次取整)的基礎上再次取整,總的說就是增加了個參數

/**
 * Created by wangyy on 2016/12/26.
 */
'use strict';
class NumberAnimate {

  constructor(opt) {
    let def = {
      from: 50, //開始時的數字
      speed: 2000, // 總時間
      refreshTime: 100, // 刷新一次的時間
      decimals: 2, // 小數點后的位數
      onUpdate: function() {}, // 更新時回調函數
      onComplete: function() {} // 完成時回調函數
    }
    this.tempValue = 0; //累加顯示變量值
    this.tempRealValue = 0; //累加真實變量值
    this.opt = Object.assign(def, opt); //assign傳入配置參數
    this.loopCount = 0; //循環次數計數
    this.loops = Math.ceil(this.opt.speed / this.opt.refreshTime); //數字累加次數
    this.increment = (this.opt.from / this.loops); //每次累加的值
    this.interval = null; //計時器對象
    this.init();
  }
  init() {
    this.interval = setInterval(() => {
      this.updateTimer()
    }, this.opt.refreshTime);
  }

  updateTimer() {
    this.loopCount++;
    //增加固定值記錄
    this.tempRealValue = this.formatFloat(this.tempRealValue, this.increment);
    this.tempValue = this.tempRealValue.toFixed(this.opt.decimals);
    if (this.loopCount >= this.loops) {
      clearInterval(this.interval);
      this.tempValue = this.opt.from;
      this.opt.onComplete();
    }
    this.opt.onUpdate();
  }
  //解決0.1+0.2不等於0.3的小數累加精度問題
  formatFloat(num1, num2) {
    let baseNum, baseNum1, baseNum2;
    try {
      baseNum1 = num1.toString().split(".")[1].length;
    } catch (e) {
      baseNum1 = 0;
    }
    try {
      baseNum2 = num2.toString().split(".")[1].length;
    } catch (e) {
      baseNum2 = 0;
    }
    baseNum = Math.pow(10, Math.max(baseNum1, baseNum2));
    return (num1 * baseNum + num2 * baseNum) / baseNum;
  };
}
export default NumberAnimate;

 再來一張小程序截圖,弄個認證又300大洋,對機會吧。。。


免責聲明!

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



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