<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
#box1{
width: 200px;
height: 200px;
background-color:cornflowerblue;
position: absolute;
}
</style>
<script>
window.onload=function(){
var box1=document.getElementById("box1");
//使div可以根据不同的方向键向不同的方向移动
//按左键,div向左。。。
//为document绑定按键按下事件
//左37,上38,右39,下40
document.onkeydown=function(event){
switch(event.keyCode){
case 37:
box1.style.left=box1.offsetLeft-10+"px";
break;
case 39:
//alert("right");
box1.style.left=box1.offsetLeft+10+"px";
break;
case 38:
//alert("up");
box1.style.top=box1.offsetTop-10+"px";
break;
case 40:
//alert("down");
box1.style.top=box1.offsetTop+10+"px";
break;
}
}
};
</script>
</head>
<body>
<div id="box1"></div>
</body>
</html>
JavaScript笔记46_键盘移动div
最新推荐文章于 2024-10-02 21:25:28 发布