目前手上有一個(gè)項(xiàng)目幻林,類似商城性質(zhì)的贞盯,有簽到,有金幣累計(jì)沪饺。產(chǎn)品提了一個(gè)需求躏敢,當(dāng)然,前篇一律整葡,后加的件余。用戶進(jìn)入頁(yè)面時(shí),當(dāng)前擁有的金幣實(shí)現(xiàn)從0動(dòng)態(tài)增加到當(dāng)前數(shù)量遭居,而不是直接變化到當(dāng)然數(shù)量啼器,也就是看的見(jiàn)的從0,1俱萍,2端壳,3.......100的增加。直接想到了n++,后來(lái)在實(shí)現(xiàn)的過(guò)程中枪蘑,如果數(shù)值特別大损谦,例如1000+,這樣過(guò)程稍長(zhǎng)岳颇。由于懶神經(jīng)發(fā)作照捡,百度了一下,沒(méi)有想要的答案话侧,索性自己就簡(jiǎn)單的封裝一個(gè)栗精。
function NumChange(opt){
var dft = {
el:'#box',//className.index會(huì)默認(rèn)為0
begin:40,
end:57,
speed:30,
}
opt&&typeof opt === 'object'?(function(){
for(var i in dft){
!opt[i]?opt[i] = dft[i]:''
}
})():opt = dft
opt.el = opt.el.indexOf('.') >-1?document.getElementsByClassName(opt.el.substring(1,opt.el.length))[0]:document.getElementById(opt.el.substring(1,opt.el.length))
this.reverse = opt.end - opt.begin>0?1:0;//判斷增減
this.levelArr = [];//存儲(chǔ)每位每次增加的數(shù) Example:[1000,100,10,1]
this.rankArr = [];//存儲(chǔ)每位數(shù) Example:[4,8,5,3]
this.splitToArr = function(){
var differ = (opt.end - opt.begin)>0?opt.end - opt.begin:opt.begin-opt.end;
var differL = differ.toString().length;
this.rankArr = differ.toString().split('').reverse();
for(var i=differL-1;i>-1;i--){
var level = Math.pow(10,differL-i-1);
this.levelArr.push(level);
}
};
this.interval = function(){
this.splitToArr();
var o = {} || null;
o.reverse = this.reverse;
o.levelArr = this.levelArr;
o.rankArr = this.rankArr;
o.rankArrL =o.rankArr.length;
o.result = opt.begin;//初始值
o.timer = null;
o.index = 0;//每一位的索引值
o.circle = 0;//每一位數(shù)值加減次數(shù)
o.interval = function(){
if(o.index == o.rankArrL){
clearInterval(o.timer)
o.timer = null;
}else{
o.circle == o.rankArr[o.index] && o.rankArr[o.index] !=0?(function(){
o.circle = 0;
o.index++;
})():'';
opt.el.innerHTML = o.result;
o.rankArr[o.index] == 0?(function(){
o.result+=0;
o.index++;
})():(function(){
o.reverse==1?o.result+=o.levelArr[o.index]:o.result-=o.levelArr[o.index];
o.circle++;
})()
}
}
o.timer = setInterval(o.interval,opt.speed);
};
this.init = function(){
opt.end == opt.el.innerHTML?'':this.interval();
}
this.init();
}
//調(diào)用
new NumChange({
el:'#box',//放置數(shù)值的element
begin:346,//初始數(shù)值
end:598,//最終數(shù)值
speed:30//變化速度
})
目前這個(gè)只是針對(duì)整數(shù)類型的,浮點(diǎn)類型的沒(méi)有做處理瞻鹏,由于時(shí)間緊术羔,滿足通用需求就行。