- 按键按下:
onkeydown
,当一直按的时候,第一个与第二个间隔时间会比较长,后面的间隔特别短,只是浏览器提供的防止误触 - 按键松开
onkeyup
键盘事件一般绑定给可以获取焦点的对象或document
- 返回按键编码:
keycode
通过方向键,控制div的移动
代码:
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
#box{
height: 100px;
width: 100px;
position: absolute;
background-color: green;
align-content: center;
}
</style>
<script>
window.onload = function(){
document.onkeydown = function(event){
event = event || window.event;
/*火狐:左上右下37 38 39 40
*/
var box = document.getElementById("box");
switch(event.keyCode){
case 37:
box.style.left = box.offsetLeft - 10 +"px";
break;
case 38:
box.style.top = box.offsetTop - 10 +"px";
break;
case 39:
box.style.left = box.offsetLeft + 10 +"px";
break;
case 40:
box.style.top = box.offsetTop + 10 +"px";
}
}
}
</script>
</head>
<body>
<div id="box"></div>
</body>
</html>