簡體   English   中英

如何使用 Javascript 移動帶有箭頭的元素

[英]how to move element with arrow using Javascript

我仍在學習 JS,我正在嘗試使用 Javascript 用箭頭移動這個 div,但每次點擊它只移動 1 步,有人可以幫我如何讓它移動更多的步驟

請檢查我的代碼

 let div = document.getElementById("test"); function move(e){ if(e.keyCode ==40){ div.style.top = 10+"px" } if(e.keyCode ==38){ div.style.top = -10+"px" } if(e.keyCode==39){ div.style.left = 10 +"px" } if(e.keyCode==37){ div.style.left = -10 +"px" } } window.onkeydown = move;
 div{ width: 200px; height: 200px; background-color: red; position: absolute; }
 <.DOCTYPE html> <html> <head> <title>index</title> <link rel="stylesheet" href="css/style.css"> </head> <body> <div id="test"></div> <script src="test.js"></script> </body> </html>

試試這個代碼,你需要當前的 position

我使用getBoundingClientRect

您也可以查看代碼而不是 keyCode

 const div = document.getElementById("test"); function move(e) { const pos = div.getBoundingClientRect() let top = pos.top; let left = pos.left; const code = e.code; switch (code) { case "ArrowRight": left += 10; break; case "ArrowLeft": left -= 10; break; case "ArrowUp": top -= 10; break; case "ArrowDown": top += 10; break; } div.style.top = `${top}px`; div.style.left = `${left}px`; } window.addEventListener("keydown",move);
 div { width: 200px; height: 200px; background-color: red; position: absolute; }
 <div id="test"></div>

您可以保存當前的 position 然后再次移動它,設置偏移量並在每次按鍵時添加/刪除距離

 const div = document.getElementById("test"); let position = 0 const offset = 10; function move(e) { if (e.keyCode == 40) { position += offset; div.style.top = position + "px" } if (e.keyCode == 38) { position -= offset; div.style.top = position + "px" } if (e.keyCode == 39) { position += offset; div.style.left = position + "px" } if (e.keyCode == 37) { position -= offset; div.style.left = position + "px" } } document.onkeydown = move;
 div { width: 200px; height: 200px; background-color: red; position: absolute; }
 <.DOCTYPE html> <html> <head> <title>index</title> <link rel="stylesheet" href="css/style.css"> </head> <body> <div id="test"></div> <script src="test.js"></script> </body> </html>

您將其偏移量設置為固定值 10 或 -10。

您需要以某種方式存儲當前的 position 並在當前的基礎上抵消新的 position。

//Intiate once at the beginning of the script
let currentVerticalPosition = 0;

if(e.keyCode ==40){
    currentVerticalPosition += 10;
    div.style.top = currentVerticalPosition +"px";
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM