運動框架
1.在開始運動時,關閉已有定時器
2.把運動和停止隔開(if/else)
勻速運動的停止條件
運動終止條件:距離足夠近
Demo代碼
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>勻速運動</title> <style> .sport { width: 60px; height: 60px; background-color: orange; border-radius: 5px; position: absolute; top: 60px; text-align: center; line-height: 60px; } #div1 { top: 60px; left: 0; } #div2 { top: 150px; left: 900px; } #reference { width: 1px; height: 260px; background-color: red; position: fixed; top: 20px; left: 450px; } </style> <script> function startMove(obj, iTarget) { let timer = null; //定時器id let oDiv1 = document.getElementById(obj); clearInterval(timer); //重點注意開啟新的定時器前,需要把舊的定時器閉關,否則會產生多個定時器! timer = setInterval(function () { let iSpeed = 0; let l = oDiv1.offsetLeft - iTarget; // l = 運動物體與目標物體之間的距離 iSpeed = l > 0 ? -8 : 8; //判斷運動方向 if (Math.abs(l) < iSpeed) { //Math.abs() 絕對值;勻速運動時,當距離l < 速度iSpeed則可以表示運動物體已到達目的地(判斷條件) clearInterval(timer); //閉關定時器 oDiv1.style.left = iTarget + 'px'; // 閉關定時器時可能運動物體只是接近目的地而非完美到達,所以需要手動設置完美抵達目的地! } else { oDiv1.style.left = oDiv1.offsetLeft + iSpeed + 'px'; //運動過程 } }, 30); } </script> </head> <body> <input type="button" value="開始運動" onclick="startMove('div1',450)" /> <input type="button" value="開始運動" onclick="startMove('div2',450)" /> <div id="div1" class="sport">A</div> <div id="div2" class="sport">B</div> <div id="reference"></div> </body> </html>
效果圖1:
效果圖2: