1. 程式人生 > >無線隨機運動-原生JS詳解

無線隨機運動-原生JS詳解

//封裝運動函式; function getStylecss(obj,oStyle){ if(obj.currentStyle){ return obj.currentStyle[oStyle]; }else{ return getComputedStyle(obj,false)[oStyle]; } } function motion(obj,json,options){ options=options || {}; options.time=options.time || 1000
; options.easing=options.easing || 'linear'; clearInterval(obj.timer); var start={}; var distance={}; for(var name in json){ start[name]=parseFloat(getStylecss(obj,name)); if(isNaN(start[name])){ switch
(name){ case 'left': start[name]=obj.offsetLeft; break; case 'top': start[name]=obj.offsetTop; break; case
'right': start[name]=obj.offsetRight; break; case 'bottom': start[name]=obj.offsetBottom; break; } } distance[name]=json[name]-start[name]; } var n=0; var count=Math.floor(options.time/30); obj.timer=setInterval(function(){ n++; for(var name in json){ switch(options.easing) { case 'linear': var a=n/count; var cur=start[name]+distance[name]*a; break; case 'ease-in': var a=n/count; var cur=start[name]+distance[name]*(a*a*a); break; case 'ease-out': var a=1-n/count; var cur=start[name]+distance[name]*(1-a*a*a); break; } if(name == 'opacity'){ obj.style[name]=start[name]+n*distance[name]/count; }else{ obj.style[name]=start[name]+n*distance[name]/count+'px'; } } if(n==count){ clearInterval(obj.timer); options.complete && options.complete(); } },30); } //頁面載入完執行以下程式碼 window.onload=function(ev){ var oDiv=document.getElementByID('target'); //封裝一個求隨機數的函式; function rnd(n,m){ return parseInt(Math.random()*(m-n)+n); } var oEvent=ev||event; var mTop=oEvent.clientHeight-oDiv.offsetHeight;//防止div身體部分跑到可視區外面,所以需要減掉物體本身的寬高; var mLeft=oEvent.clientWidth-oDiv.offsetWidth; function move(){ motion(oDiv,{left:rnd(1,mLeft),toprnd(1,mTop)},{complete:function(){ move();//讓這個函式永遠執行; }}); } move(); }