<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>keydown</title> <style> *{ margin: 0; padding: 0; } #box{ width: 200px; height: 200px; background-color: rebeccapurple; } </style> </head> <body> <div id="box" style="position: absolute;left: 0px;top: 0px;"></div> </body> <script> var box = document.getElementById("box"); document.body.onkeydown = function (e) { var ent = e || window.event; switch(ent.keyCode) { case 37: box.style.left = parseFloat(box.style.left) - 10 + "px"; break; case 38: box.style.top = parseFloat(box.style.top) - 10 + "px"; break; case 39: box.style.left = parseFloat(box.style.left) + 10 + "px"; break; case 40: box.style.top = parseFloat(box.style.top) + 10 + "px"; break; default: break; } } </script> </html>
JavaScript按键拖动
最新推荐文章于 2023-04-10 09:19:08 发布