<!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 {
width: 100px;
height: 100px;
background-color: red;
/* 基于body */
position: absolute;
top: 0px;
left: 100px;
}
</style>
</head>
<body>
<div class="box"></div>
</body>
<script>
const box = document.querySelector(".box");
//设置键盘监听
window.onkeydown = function (event) {
//获取box距离父亲上边和左边的距离
const offsetTop = box.offsetTop;
console.log(offsetTop);
const offsetLeft = box.offsetLeft;
console.log(offsetLeft);
//获取按键,实现aswd;
switch (event.key) {
case "a":
box.style.left = offsetLeft - 2 + "px";
console.log("a");
break;
case "s":
box.style.top = offsetTop + 2 + "px";
console.log("s");
break;
case "w":
box.style.top = offsetTop - 2 + "px";
console.log("w");
break;
case "d":
box.style.left = offsetLeft + 2 + "px";
console.log("d");
break;
default:
break;
}
};
</script>
</html>
JS元素跟着键盘上下左右移动
最新推荐文章于 2023-12-12 18:23:00 发布