移動端動畫
紅色勾勾代表強(qiáng)烈推薦
transition實現(xiàn)動畫案例: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>移動端動畫</title> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no"> <style> *{padding:0;margin:0;} .box{width:100px;height: 100px;background-color: pink;transition:transform 1s;} </style> </head> <body> <button id="btn">start</button> <div class="box" id="box"></div> <script> var btn=document.getElementById("btn"), box=document.getElementById("box"), dest=window.innerWidth-100;//移動的距離 btn.addEventListener("click",function(){ box.style.transform="translate3d("+dest+"px,0,0)"; },false); </script> </body> </html>
也可以提取成函數(shù)的寫法: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>移動端動畫</title> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no"> <style> *{padding:0;margin:0;} .box{width:100px;height: 100px;background-color: pink;transition:transform 1s;} </style> </head> <body> <button id="btn">start</button> <div class="box" id="box"></div> <script> var btn=document.getElementById("btn"), box=document.getElementById("box"), dest=window.innerWidth-100;//移動的距離 btn.addEventListener("click",function(){ move(box,dest); },false); function move(el,pos){ el.style.transform="translate3d("+pos+"px,0,0)"; } </script> </body> </html>
animation動畫推薦一個animation庫,animation.js https://daneden./animate.css/ 可以查看各種動畫的樣式:
一般情況下推薦使用css3的transition和animation來完成動畫,如果不能滿足需求,可以考慮js的requestAnimationFrame 不做css動畫時,記得一定要去掉transition屬性 requestAnimationFrame的特點是:調(diào)用一次只執(zhí)行一幀;如果想要持續(xù)執(zhí)行,就需要遞歸。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>移動端動畫</title> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no"> <style> *{padding:0;margin:0;} .box{width:100px;height: 100px;background-color: pink;} </style> </head> <body> <button id="btn">start</button> <div class="box" id="box"></div> <script> //requestAnimationFrame的兼容性處理 var requestAnimationFrame=window.requestAnimationFrame|| window.webkitRequestAnimationFrame|| window.mozRequestAnimationFrame|| window.msRequestAnimationFrame|| window.oRequestAnimationFrame|| function(fn){ setTimeout(fn,16); } var btn=document.getElementById("btn"), box=document.getElementById("box"), dest=window.innerWidth-100,//移動的距離 speed=1, pos=0; btn.addEventListener("click",function(){ requestAnimationFrame(step); },false); function move(el,pos){ el.style.transform="translate3d("+pos+"px,0,0)"; } function step(){ if(pos<dest){ //遞歸 pos+=speed; move(box,pos); requestAnimationFrame(step); }else{ pos=dest; move(box,pos); } } </script> </body> </html>
|
|