事件对象之键盘
事件对象e: charcode keycode
charcode用于onkeypress
keycode用于onkeyup/down
onkeypress用于字符
onkeyup/down用于按键
37-40左顺 0-9:48-- a-z:97-- A-Z:65–
小例子: 按方向键控制盒子移动
在这里插入代码片
<!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>事件对象之键盘</title>
<style>
* {
margin: 0;
padding: 0;
}
#box {
width: 200px;
height: 200px;
background-color: green;
position: absolute;
left: 100px;
top: 100px;
}
</style>
</head>
<body>
<!-- 按方向键控制盒子移动 -->
<div id="box"></div>
</body>
<script>
var obox = document.getElementById('box')
var l = 100
var t = 100
// document对整个网页起作用
document.onkeydown = function (e) {
switch (e.keyCode) {
case 37:
l -= 5;
break;
case 38:
t -= 5;
break;
case 39:
l += 5;
break;
case 40:
t += 5;
break;
}
obox.style.left = l + 'px'
obox.style.top = t + 'px'
}
</script>
</html>