<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.box {
/* 绝对定位 */
position: absolute;
width: 100px;
/* top left 在其中相当于xy轴 */
top: 0px;
left: 0px;
background-color: aqua;
}
</style>
</head>
<body>
<img src="https://ts1.cn.mm.bing.net/th/id/R-C.1f3d2ce28390ac97105aefa89ddd0fba?rik=Lddw7qEBwvfhFA&riu=http%3a%2f%2fimg1.duote.com%2fduoteimg%2fdtnew_newsup_img%2f202102%2f20210203092954_62143.jpg&ehk=V7s7t%2fvKvw%2fXG4YxnFWYWz7JJ6Z%2f62NdmONAQVALDdc%3d&risl=&pid=ImgRaw&r=0"
alt="" class="box">
<script>
var Box = document.getElementsByClassName("box")[0];// 获取盒子
var oleft = 0;
var otop = 0;
window.onkeydown = function (e) { //定义函数 键盘按下事件
if (e.keyCode == 37) { //向左 获取键盘10进制keyCode
oleft = oleft - 5;
Box.style.left = oleft + "px";
} else if (e.keyCode == 39) { //向右 获取键盘10进制keyCode
oleft = oleft + 5;
Box.style.left = oleft + "px";
} else if (e.keyCode == 38) { //向上 获取键盘10进制keyCode
otop = otop - 5;
Box.style.top = otop + "px";
} else if (e.keyCode == 40) { //向下 获取键盘10进制keyCode
otop = otop + 5;
Box.style.top = otop + "px";
}
}
</script>
</body>
</html>
键盘事件移动
最新推荐文章于 2024-11-08 11:00:36 发布