<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<style>
#box1{
width: 100px;
height: 100px;
background-color: red;
position: absolute;
}
</style>
<script type="text/javascript">
window.onload = function(){
var box1 = document.getElementById("box1");
document.onkeydown = function(event){
var speed = 15;
if(event.ctrlKey){
speed = 200;
}
switch(event.keyCode){
case 37:
box1.style.left = box1.offsetLeft - speed + "px";
break;
case 39:
box1.style.left = box1.offsetLeft + speed + "px";
break;
case 38:
box1.style.top = box1.offsetTop - speed + "px";
break;
case 40:
box1.style.top = box1.offsetTop + speed + "px";
break;
}
}
}
</script>
</head>
<body>
<div id="box1"></div>
</body>
</html>
改进版
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<style>
#box1{
width: 100px;
height: 100px;
background-color: red;
position: absolute;
}
</style>
<script type="text/javascript">
window.onload = function(){
var speed = 15;
var dir = 0;
setInterval(function(){
switch(dir){
case 37:
box1.style.left = box1.offsetLeft - speed + "px";
break;
case 39:
box1.style.left = box1.offsetLeft + speed + "px";
break;
case 38:
box1.style.top = box1.offsetTop - speed + "px";
break;
case 40:
box1.style.top = box1.offsetTop + speed + "px";
break;
}
}, 30);
var box1 = document.getElementById("box1");
document.onkeydown = function(event){
if(event.ctrlKey){
speed = 45;
}else{
speed = 15;
};
dir = event.keyCode;
};
document.onkeyup = function(){
dir = 0;
};
};
</script>
</head>
<body>
<div id="box1"></div>
</body>
</html>