简体   繁体   中英

how to move element with arrow using Javascript

I'm still learning JS and I'm trying to move this div with arrows using Javascript but it moves only 1 step per click can someone please help me how to make it moves more steps

check my code please

 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>

Try this code, you need the current position

I use getBoundingClientRect

You might also look at code instead of 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>

You can save the current position then move it again, set an offset and add/remove distance at every keydown

 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>

You are setting its offset to a fixed value of 10 or -10.

You need to store the current position somehow and offset the new position based on the current one.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM