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


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

  • 相关阅读:
    jssdk语音识别调用(基于easywechat)
    mysql常见问题
    JAVA常见面试题
    使用HttpClient实现文件上传和下载
    mysql之数据去重并记录总数
    mysql的BLOB类型问题
    Velocity入门总结
    关于JSON的一些问题
    QLExpress语法介绍
    史上最全的Maven Pom文件标签详解(转)
  • 原文地址:https://www.cnblogs.com/wangbg/p/12019526.html
Copyright © 2020-2023  润新知