键盘移动div
2025年4月30日小于 1 分钟
示例代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>键盘移动div</title>
<style type="text/css">
*
{
margin:0px;
padding:0px;
}
#dv
{
width:200px;
height:200px;
background:#c81623;
position:absolute;
top:0px;
left:0px;
}
</style>
</head>
<body>
<div id='dv'></div>
<script type="text/javascript">
//获取对象
var dv=document.getElementById('dv');
//键盘按下事件
window.onkeydown=function(e)
{
//console.log(e);
// keyCode每个键盘对应的数值
var num=e.keyCode;
//每歩的步数
var step=5;
switch(num)
{
//上
case 87:
case 38:
var t=dv.offsetTop;
var th=t-step;
dv.style.top=th+'px';
break;
//下
case 40:
case 83:
var t=dv.offsetTop;
var th=t+step;
dv.style.top=th+'px';
break;
//左
case 37:
case 65:
var l=dv.offsetLeft;
var lh=l-step;
dv.style.left=lh+'px';
break;
//右
case 68:
case 39:
var l=dv.offsetLeft;
var lh=l+step;
dv.style.left=lh+'px';
break;
}
return false;
}
window.oncontextmenu=function()
{
return false;
}
</script>
</body>
</html>