繁体   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