setInterval動畫運動平移,定時器動畫練習
阿新 • • 發佈:2019-01-04
常見問題:定時器加速問題,每次點選會啟動一個定時器,解決先清楚
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>動畫運動平移</title> <style> *{margin:0;padding:0;} #aa1 {position:absolute;left:0;width:100px;height:100px;background:#F00;display:inline-block;} #btn1 {position:absolute;top:120px;} .line {position:absolute;left:300px;width:1px;height:500px;background:#000;} </style> </head> <body> <input type="button" value = "移動" id="btn1"> <div id="aa1"></div> <div id="aa2"></div> <div class='line'></div> <script> //定時器加速問題,每次點選會啟動一個定時器,解決先清楚 var oBtn1 = document.querySelector('#btn1'); var oDiv1 = document.querySelector('#aa1'); var timer=null; oBtn1.onclick=function(){ var speed=1; clearInterval(timer); timer = setInterval(function(){ oDiv1.style.left=oDiv1.offsetLeft+speed+'px'; if(oDiv1.offsetLeft>=300){ oDiv1.style.left=300+'px'; clearInterval(timer); timer =null; } },20) } </script> </body> </html>