vue怎么按键盘上下左右使div移动,求大神进行解答,小弟感激不尽
2条回答 默认 最新
CSDN专家-赖老师(软件之家) 2021-11-12 20:26关注<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>方向键移动div</title> <style> #box1 { width: 200px; height: 200px; background-color: aqua; position: absolute; } </style> <script> window.onload = function () { var b1 = document.getElementById("box1"); var distance = 10; alert("按下ctrl键加速,按下alt键减速"); document.onkeydown = function (event) { event = event || window.event; if (event.ctrlKey) { distance = 40; } if (event.shiftKey) { distance = 5; } if (event.keyCode === 37) { b1.style.left = b1.offsetLeft - distance + "px"; } else if (event.keyCode === 38) { b1.style.top = b1.offsetTop - distance + "px"; } else if (event.keyCode === 39) { b1.style.left = b1.offsetLeft + distance + "px"; } else if (event.keyCode === 40) { b1.style.top = b1.offsetTop + distance + "px"; } }; }; </script> </head> <body> <div id="box1"></div> </body>本回答被题主选为最佳回答 , 对您是否有帮助呢?评论 打赏 举报解决 1无用 1