通过键盘事件实现div移动
<style>
.box {
width: 200px;
height: 200px;
background-color: skyblue;
position: absolute;
top: 200px;
left: 200px;
}
</style>
</head>
<body>
<div class="box"></div>
<script>
//获取div的对象节点
let box = document.querySelector(".box");
// 使用键盘事件实现div的移动
document.onkeydown = function (e) {
// console.log(e.keyCode);
//分别对应着左上右下。
let code = e.keyCode;
switch (code) {
case 37: box.style.left = box.offsetLeft - 5 + "px"; break;
case 38: box.style.top = box.offsetTop - 5 + "px"; break;
case 39: box.style.left = box.offsetLeft + 5 + "px"; break;
case 40: box.style.top = box.offsetTop + 5 + "px"; break;
}
}
</script>
</body