微信小程序数字累加动态效果完善
问题描述:最近做了个关于记事的微信小程序,结果因为是个人主体,没给审核通过,看来还是自己用吧。。。里面涉及到了一个数字累加的效果实现,百度到了一篇 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大洋,对机会吧。。。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!