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;
}
}
答案 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