1. 键盘的按键事件
2.键盘事件的事件对象
3.案例:通过键盘上下左右控制标签移动
<!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>
* {
margin: 0;
padding: 0;
}
div {
width: 600px;
height: 600px;
padding: 100px;
border: 20px solid paleturquoise;
background: rgb(160, 241, 160);
display: flex;
justify-content: center;
align-items: center;
margin: 200px auto;
position: relative;
}
p {
width: 50px;
height: 50px;
padding: 50px;
border: 10px solid orange;
background: pink;
position: absolute;
}
</style>
</head>
<body>
<div>
<p></p>
</div>
<script>
var oDiv = document.querySelector('div');
var oP = document.querySelector('p');
let oDivWidth = oDiv.clientWidth;
let oDivHeight = oDiv.clientHeight;
let oPWidth = oP.offsetWidth;
let oPHeight = oP.offsetHeight;
document.addEventListener('keydown', function (e) {
if (e.keyCode === 37) {
let oPLeft = parseInt(window.getComputedStyle(oP).left);
oPLeft -= 5;
oPLeft = oPLeft < 0 ? 0 : oPLeft;
oP.style.left = oPLeft + 'px';
} else if (e.keyCode === 38) {
let oPTop = parseInt(window.getComputedStyle(oP).top);
oPTop -= 5;
oPTop = oPTop < 0 ? 0 : oPTop
oP.style.top = oPTop + 'px';
} else if (e.keyCode === 39) {
let oPLeft = parseInt(window.getComputedStyle(oP).left);
oPLeft += 5;
oPLeft = oPLeft > oDivWidth - oPWidth ? oDivWidth - oPWidth : oPLeft;
oP.style.left = oPLeft + 'px';
} else if (e.keyCode === 40) {
let oPTop = parseInt(window.getComputedStyle(oP).top);
oPTop += 5;
oPTop = oPTop > oDivHeight - oPHeight ? oDivHeight - oPHeight : oPTop;
oP.style.top = oPTop + 'px';
}
})
</script>
</body>
</html>