js实现简单数字变动效果
本文实例为大家分享了js实现数字变动效果展示的具体代码,供大家参考,具体内容如下
$.fn.countTo=function(options){
options=options||{};//当options未被初始化,即typeofoptions='undefined'时,执行后面部分即varoptions={}来初始化一个对象
return$(this).each(function(){
//setoptionsforcurrentelement
varsettings=$.extend({},$.fn.countTo.defaults,{
from:$(this).data('from'),
to:$(this).data('to'),
speed:$(this).data('speed'),
refreshInterval:$(this).data('refresh-interval'),
decimals:$(this).data('decimals')
},options);
//howmanytimestoupdatethevalue,andhowmuchtoincrementthevalueoneachupdate
//更新值多少次,每次更新值多快
varloops=Math.ceil(settings.speed/settings.refreshInterval),
increment=(settings.to-settings.from)/loops;
//references&variablesthatwillchangewitheachupdate
//引用和变量每次更新将改变
varself=this,//返回html对象
$self=$(this),//返回返回一个jquery对象
loopCount=0,
value=settings.from,
data=$self.data('countTo')||{};//获取jauery方法对象
$self.data('countTo',data);//赋值
//ifanexistingintervalcanbefound,clearitfirst
//如果存在间隔,则清除它
if(data.interval){
clearInterval(data.interval);
}
data.interval=setInterval(updateTimer,settings.refreshInterval);
//initializetheelementwiththestartingvalue
//用开始的值初始化
render(value);
functionupdateTimer(){
value+=increment;
loopCount++;
render(value);
if(typeof(settings.onUpdate)=='function'){
settings.onUpdate.call(self,value);
}
if(loopCount>=loops){
//removetheinterval
$self.removeData('countTo');
clearInterval(data.interval);
value=settings.to;
if(typeof(settings.onComplete)=='function'){
settings.onComplete.call(self,value);
}
}
}
functionrender(value){
varformattedValue=settings.formatter.call(self,value,settings);
$self.html(formattedValue);
}
});
};
$.fn.countTo.defaults={
from:200,//thenumbertheelementshouldstartat
to:0,//thenumbertheelementshouldendat
speed:1000,//howlongitshouldtaketocountbetweenthetargetnumbers
refreshInterval:1,//howoftentheelementshouldbeupdated
decimals:0,//thenumberofdecimalplacestoshow
formatter:formatter,//handlerforformattingthevaluebeforerendering
onUpdate:null,//callbackmethodforeverytimetheelementisupdated
onComplete:null//callbackmethodforwhentheelementfinishesupdating
};
functionformatter(value,settings){
returnvalue.toFixed(settings.decimals);
}
//customformattingexample
$('#count-number').data('countToOptions',{
formatter:function(value,options){
returnvalue.toFixed(options.decimals).replace(/\B(?=(?:\d{3})+(?!\d))/g,',');
}
});
//startallthetimers
$('.timer').each(count);
functioncount(options){
var$this=$(this);
options=$.extend({},options||{},$this.data('countToOptions')||{});
$this.countTo(options);
}
apply与call的简单用法,学习链接。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
热门推荐
10 小红书平安祝福语简短
11 生日祝福语大全女孩简短
12 收生日红包祝福语 简短
13 领证幽默祝福语简短
14 法考面试祝福语简短
15 老哥出门祝福语简短语
16 送灯祝福语简短独特
17 幼儿狗年祝福语大全简短
18 好听的元旦简短祝福语