js 键盘事件

来源:互联网 发布:西游之路魔兵进阶数据 编辑:程序博客网 时间:2024/04/28 20:03
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
</head>
<body>
<div id="dSquare" style="background:#0000FF;POSITION: absolute; width:20px; height:20px; top:50px; left:200px;"></div>
</body>
</html>
<script language=javascript> 
if(typeof GetControl=="undefined") GetControl=function (id)
{
    
return document.getElementById(id);
}
;

var control=GetControl("dSquare");
function KeyDown(e) {                  
            
var key;
            
try
                   key
=event.keyCode;  //取得键盘Code编号
             }
 
             
catch(a)//对于Firefox来说,不支持event.keyCode
                   key=KeyDown.arguments[0].keyCode; 
             }
 
             
            
switch(key)
            
{
                
case 40://40 == down
                    control.style.top=(parseInt(control.style.top)+1)+ "px";            
                    
break;
                
case 39://39 == right
                    control.style.left=(parseInt(control.style.left)+1)+ "px";
                    
break;
                
case 38://38 == up
                    control.style.top=(parseInt(control.style.top)-1)+ "px";
                    
break;
                
case 37://37 == left    
                    control.style.left=(parseInt(control.style.left)-1)+ "px";
                    
break;                    
            }

}
 
document.onkeydown
=KeyDown; //附加事件
document.onkeypress=KeyDown; //附加事件
</script>
 
原创粉丝点击