javascript:用键盘移动盒子代码(键盘事件)

 1 <html>
 2 <head>
 3 <title>1title>
 4 <style type='text/css'>
 5 #box{
 6     width:100px;
 7     height:100px;
 8     position:absolute;
 9     left:300px;
10     top:200px;
11     border:solid 1px green;
12 }
13 style>
14 head>
15 <body>
16 <div id='box'>div>
17 <script language='javascript'>
18     //document.getElementById('box').onkeydown 点击div块获得焦点就能响应该事件
19     document.onkeydown=function(){
20         var obj=document.getElementById('box');
21         var left=obj.offsetLeft;
22         var top=obj.offsetTop;
23         var x;
24         var y;
25         switch(event.keyCode){
26             case 37:
27                 x=left-10;
28                 break;
29             case 39:
30                 x=left+10;
31                 break;
32             case 38:
33                 y=top-10;
34                 break;
35             case 40:
36                 y=top+10;
37                 break;
38         }
39         if(x){
40             obj.style.left=x+'px';
41         }
42         if(y){
43             obj.style.top=y+'px';
44         }
45     }
46 script>
47 
48 body>
49 html>

 

转载于:https://www.cnblogs.com/51xzdy/archive/2012/06/05/2535550.html

你可能感兴趣的:(javascript)