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

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);

慕码人8056858
浏览 434回答 1
1回答

三国纷争

不知道你这个speedX、Y是什么意思,但是上面的事件应该是document.onkeydown,不是keydown  
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript