在開(kāi)發(fā)過(guò)程中經(jīng)常會(huì)遇到數(shù)字從0不斷變動(dòng)的動(dòng)畫(huà)效果,在接到這樣的需求后囱桨,我第一時(shí)間想到了通過(guò)計(jì)時(shí)器的方式對(duì)數(shù)字進(jìn)行不斷的更改司顿,以實(shí)現(xiàn)這樣的變動(dòng)效果。具體代碼如下:
// 數(shù)字動(dòng)效
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);
}
//設(shè)置數(shù)字動(dòng)效的id列表以便后面遍歷創(chuàng)建numberAction動(dòng)效
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();
}