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);
添加回答
举报
0/150
提交
取消