微信小程序数字累加动态效果完善

问题描述:最近做了个关于记事的微信小程序,结果因为是个人主体,没给审核通过,看来还是自己用吧。。。里面涉及到了一个数字累加的效果实现,百度到了一篇 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;

猜你喜欢

转载自www.cnblogs.com/wangbg/p/12019526.html