键盘控制div移动
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style>
#div1{
width: 100px;
height: 100px;
background: red;
position: absolute;
}
</style>
<script>
window.onload=function(){
//不是所有元素都能够接受键盘事件,能够响应用户输入的元素
//能够接受焦点的元素就能够接受键盘事件
// onkeydown:如果按下不抬起会连续触发
var oDiv=document.getElementById("div1");
document.onkeydown=function(ev){
var ev=ev||event;
switch(ev.keyCode){
case 37:
oDiv.style.left=oDiv.offsetLeft-10+"px";
break;
case 38:
oDiv.style.top=oDiv.offsetTop-10+"px";
break;
case 39:
oDiv.style.left=oDiv.offsetLeft+10+"px";
break;
case 40:
oDiv.style.top=oDiv.offsetTop+10+"px";
break;
}
}
}
</script>
</head>
<body>
<div id="div1"></div>
</body>
</html>

浙公网安备 33010602011771号