!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
#box1{
width:100px;
height: 100px;
background-color:red ;
position: absolute;
}
</style>
<script type="text/javascript">
//使div可以根据不同的方向键向不同方向移动
/*
* 按左键,div向左移动
* 按右键,div向右移动
*/
window.onload = function(){
//为document绑定一个按键按下的事件
document.onkeydown = function(event){
event = event ||window.event
//定义一个变量,来表示移动的速度
var speed = 10;
//当用户按了CTRL以后,速度加快
if(event.ctrlKey){
speed = 220;
};
/*
* 37左
* 38上
* 39右
* 40下
*/
switch(event.keyCode){
case 37:
// alert('向左');left
box1.style.left = box1.offsetLeft - speed+"px";
break;
case 39:
// alert("向右");
box1.style.left = box1.offsetLeft + speed+"px";
break;
case 38:
// alert("向上");
box1.style.top =
JavaScript中用方向键来移动方块
最新推荐文章于 2021-10-07 10:05:26 发布