微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

微信小程序数字滚动插件使用详解

用es6语法方式写了个微信小程序插件–数字滚动;

效果图:

wxml页面布局代码

rush:xml;"> Box">

index.js调用NumberAnimate.js

// 页面显示
},onHide:function(){
// 页面隐藏
},onUnload:function(){
// 页面关闭
},//调用NumberAnimate.js中NumberAnimate实例化对象,测试3种效果
animate:function(){

this.setData({
num1:'',num2:'',num3:'',num1Complete:'',num2Complete:'',num3Complete:''
});

let num1 = 18362.856;
let n1 = new NumberAnimate({
from:num1,//开始时的数字
speed:2000,// 总时间
refreshTime:100,// 刷新一次的时间
decimals:3,//小数点后的位数
onUpdate:()=>{//更新回调函数
this.setData({
num1:n1.tempValue });
},onComplete:()=>{//完成回调函数
this.setData({
num1Complete:" 完成了"
});
}
});

let num2 = 13388;
let n2 = new NumberAnimate({
from:num2,speed:1500,decimals:0,refreshTime:100,onUpdate:()=>{
this.setData({
num2:n2.tempValue });
},onComplete:()=>{
this.setData({
num2Complete:" 完成了"
});
}
});

let num3 = 2123655255888.86;
let n3 = new NumberAnimate({
from:num3,speed:2000,decimals:2,onUpdate:()=>{
this.setData({
num3:n3.tempValue });
},onComplete:()=>{
this.setData({
num3Complete:" 完成了"
});
}
});
}})

NumberAnimate.js代码

constructor(opt) {
let def = {
from:50,//开始时的数字
speed:2000,// 总时间
refreshTime:100,// 刷新一次的时间
decimals:2,// 小数点后的位数
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;

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程之家。

原文地址:https://www.jb51.cc/weapp/33891.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。