JS练习_键盘事件
预览:
源码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>事件类型</title>
<style>
.box{
width: 200px;
height: 200px;
background-color: red;
position: absolute;
top: 100px;
left: 100px;
}
</style>
</head>
<body>
<div class="box"></div>
<script>
let box= document.querySelector(".box");
console.log(box.offsetTop);// 获取box的距顶部的距离
// 键盘按下事件
document.onkeydown = function (e){
// console.log(e.keyCode);// 打印键盘锁对应的编码
let code = e.keyCode;
switch (code){
case 37:
console.log("左键");
box.style.left = box.offsetLeft - 5 + "px";
break;
case 38:
console.log("上键");
box.style.top = box.offsetTop - 5 + "px";
break;
case 39:
console.log("右键");
box.style.left = box.offsetLeft + 5 + "px";
break;
case 40:
console.log("下键");
box.style.top = box.offsetTop + 5 + "px";
break;
}
}
</script>
</body>
</html>
把最实用的经验,分享给最需要的读者,希望每一位来访的朋友都能有所收获!