小程序数字滚动

js文件
class NumberAnimate {
constructor(opt) {
let def = {
from: 0, //开始时的数字
speed: 2000, // 总时间
refreshTime: 100, // 刷新一次的时间
decimals: 0, // 小数点后的位数
onUpdate: function () {}, // 更新时回调函数
onComplete: function () {} // 完成时回调函数
}
this.tempValue = 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.tempValue = this.formatFloat(this.tempValue, this.increment).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;
引入 import NumberAnimate from “…/…/components/NumberAnimate”;
// 数字滚动
animate: function () {
let num1 = this.data.actionNum;
let n1 = new NumberAnimate({
from: num1, //开始时的数字
speed: 2000, // 总时间
refreshTime: 100, // 刷新一次的时间
decimals: 2, //小数点后的位数
onUpdate: () => { //更新回调函数
this.setData({
rollMoney: n1.tempValue
});
}
})
},
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值