在开发过程中经常会遇到数字从0不断变动的动画效果,在接到这样的需求后,我第一时间想到了通过计时器的方式对数字进行不断的更改,以实现这样的变动效果。具体代码如下:
// 数字动效
var numberAction = function (id, number) {
this.id = id;
this.number = number ? number : Number($(id).html());
}
numberAction.prototype.start = function () {
// time单位为ms
var _this = this, num = 0;
this.flag = setInterval(function () {
var the_int = _this.number.toFixed(0);
var last = (_this.number - num);
if (last > 100000) {
num = Number(num) + 100000;
} else if (last > 10000) {
num = Number(num) + 10000;
} else if (last > 1000) {
num = Number(num) + 1000;
} else if (last > 100) {
num = Number(num) + 100;
} else if (last > 10) {
num = Number(num) + 10;
} else if (last > 1) {
num = Number(num) + 1;
} else if (last <= 0) {
console.log(num, _this.number)
clearInterval(_this.flag);
}
$(_this.id).html(num)
}, 80);
}
//设置数字动效的id列表以便后面遍历创建numberAction动效
var numberlist = ["#num-1", "#num-2", "#num-3", "#num-4", "#num-5", "#num-6", "#num-7", "#num-8", "#num-9"];
for (var i = 0; i < numberlist.length; i++) {
var number = new numberAction(numberlist[i]);
number.start();
}