首页新闻找找看学习计划

想通过按键控制一个块移动,这段代码为何不起作用

0
[已解决问题] 解决于 2016-09-25 11:31

document.keydown = function(event){
var event = event || window.event;
var keyCode = event.keyCode || event.which;
switch(keyCode){
case 37:
if(speedX == 0){
speedX = -1;
speedY = 0;
}
break;
case 38:
if(speedY == 0){
speedX = 0;
speedY = -1;
}
break;
case 39:
if (speedX == 0){
speedX = 1;
speedY = 0;
}
break;
case 40:
if(speedY == 0){
speedX = 0;
speedY = 1;
}
break;
default:
return;
break;
}
boxMove();
}

 

控制台没有报错,元素获取也没有问题

但是用下面这段就可以,为什么会这样

document.addEventListener("keydown",function(event){
var event = event || window.event;
var keyCode = event.keyCode || event.which;

switch(keyCode){
case 37:
if(speedX == 0){
speedX = -1;
speedY = 0;
}
break;
case 38:
if(speedY == 0){
speedX = 0;
speedY = -1;
}
break;
case 39:
if(speedX == 0){
speedX = 1;
speedY = 0;
}
break;
case 40:
if(speedY == 0){
speedX = 0;
speedY = 1;
}
break;
default:
return;
break;
}
boxMove();
},false);

sahk的主页 sahk | 初学一级 | 园豆:110
提问于:2016-09-03 11:15
< >
分享
最佳答案
0

不知道你这个speedX、Y是什么意思,但是上面的事件应该是document.onkeydown,不是keydown

 

奖励园豆:5
凌晨肆丶的洛杉矶 | 初学一级 |园豆:138 | 2016-09-05 14:35
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册