<!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>
本文介绍了一种使用JavaScript实现键盘按键控制HTML页面中指定元素移动的方法。通过监听键盘事件,根据用户按下不同的方向键(上、下、左、右),调整指定HTML元素的位置属性,使该元素能在页面上按方向键指示的方向移动。
5535

被折叠的 条评论
为什么被折叠?



