Keylistener in Javascript

2019-01-14 12:01发布

I'm looking for a key listener for a game I'm developing in JavaScript. I have no idea how this would work in real code but it would be somthing like this.

    if(keyPress=upKey)
     {
      playerSpriteX+=10;

     }
    else if(keyPress=downKey)
     {
      playerSpriteY-=10;

     } 

ect...

I searched it up, and Google came up with things that involved AJAX which I don't understand yet. Is there a built in function in javascript that does this?

5条回答
我只想做你的唯一
2楼-- · 2019-01-14 12:41

The code is

document.addEventListener('keydown', function(event){
    alert(event.keyCode);
} );

This return the ascii code of the key. If you need the key representation, use event.key (This will return 'a', 'o', 'Alt'...)

查看更多
男人必须洒脱
3楼-- · 2019-01-14 12:41

A bit more readable comparing is done by casting event.key to upper case (I used onkeyup - needed the event to fire once upon each key tap):

window.onkeyup = function(event) {
    let key = event.key.toUpperCase();
    if ( key == 'W' ) {
        // 'W' key is pressed
    } else if ( key == 'D' ) {
        // 'D' key is pressed
    }
}

Each key has it's own code, get it out by outputting value of "key" variable (eg for arrow up key it will be 'ARROWUP' - (casted to uppercase))

查看更多
神经病院院长
4楼-- · 2019-01-14 12:45

JSFIDDLE DEMO

If you don't want the event to be continuous (if you want the user to have to release the key each time), change onkeydown to onkeyup

window.onkeydown = function (e) {
    var code = e.keyCode ? e.keyCode : e.which;
    if (code === 38) { //up key
        alert('up');
    } else if (code === 40) { //down key
        alert('down');
    }
};
查看更多
Lonely孤独者°
5楼-- · 2019-01-14 12:50
window.onkeyup = function(e) {
   var key = e.keyCode ? e.keyCode : e.which;

   if (key == 38) {
       playerSpriteX += 10;
   }else if (key == 40) {
       playerSpriteX -= 10;
   }
}

FIDDLE

查看更多
别忘想泡老子
6楼-- · 2019-01-14 12:59

Did you check the small Mousetrap library?

Mousetrap is a simple library for handling keyboard shortcuts in JavaScript.

查看更多
登录 后发表回答