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);
不知道你这个speedX、Y是什么意思,但是上面的事件应该是document.onkeydown,不是keydown