標籤:absolute blog meta position time var 基礎 script alt
<!DOCTYPE html><html><head lang="en"> <meta charset="UTF-8"> <title></title> <style> #div1{ width: 200px; height: 200px; background: red; position: absolute; top:50px; left: 0px; } </style> <script> function startMove(){ var oDiv=document.getElementById(‘div1‘); setInterval(function(){ oDiv.style.left=oDiv.offsetLeft+10+‘px‘; },30) } </script></head><body><input id="btn1" type="button" value="開始運動" onclick="startMove()"> <div id="div1" ></div></input></body></html>
設定停頓位置和移動速度
<!DOCTYPE html><html><head lang="en"> <meta charset="UTF-8"> <title></title> <style> #div1{ width: 200px; height: 200px; background: red; position: absolute; top:50px; left: 0px; } </style> <script> //開啟定時器 var timer=null; function startMove(){ var speed=3; var oDiv=document.getElementById(‘div1‘); timer=setInterval(function(){ if(oDiv.offsetLeft>=300){//停頓位置 clearInterval(timer); } oDiv.style.left=oDiv.offsetLeft+speed+‘px‘;//speed是物體運動速度快慢 },30); } </script></head><body><input id="btn1" type="button" value="開始運動" onclick="startMove()"> <div id="div1" ></div></input></body></html>
JS運動基礎