在javascript中检测两个键盘按钮

时间:2015-02-28 11:22:20

标签: javascript

我正在编写一个简单的画布游戏,并希望能够在屏幕上对角移动我的角色。如何检测按下的两个按键说出来? 继到目前为止我的代码 -

function keyHit(evt){
switch (evt.keyCode) {
case 38:  /* Up arrow was pressed */
if (player2y >= 1){
player2y -= 4;
 } else {player2y = 0;}
break;
case 40:  /* Down arrow was pressed */
if (player2y <= 364){
player2y += 4;
} else { player2y = 365;}
break;
case 37:  /* Left arrow was pressed */
if (player2x >= 1){
player2x -= 4;
} else {player2x = 0;}
break;
case 39:  /* Right arrow was pressed */
if (player2x <= 665){
player2x += 4;
} else {player2x = 666;}
break;
}
}

1 个答案:

答案 0 :(得分:2)

陷阱“keydown”和“keyup”事件并维护当前按下的键列表。例如:

pressed = {}


window.onkeydown = function(e) {
  pressed[e.keyCode] = 1
  handler(Object.keys(pressed).sort())
}

window.onkeyup = function(e) {
  delete pressed[e.keyCode];
  handler(Object.keys(pressed).sort())
}

function handler(pressed) {
  document.getElementById("log").value = pressed
  if(pressed == "38,39")
    alert("Up+Right pressed!")
}  
<textarea id="log"></textarea><br>click here first, then press some keys