How to find the key code for a specific key

后端 未结 11 2037
猫巷女王i
猫巷女王i 2020-12-28 09:29

What\'s the easiest way to find the keycode for a specific key press?

Are there any good online tools that just capture any key event and show the code?

I wa

相关标签:
11条回答
  • 2020-12-28 10:20

    If you are only looking for keyCode you essentially don't need to get the keypress event, you can simply convert character to keyCode and vise versa:

    Char to KeyCode, for instance A ("A").charCodeAt(0) returns 65. Here's the syntax.

    If you already know the characters which their keycodes are needed, say 'ABCDEFGH', you only need a loop to get all key codes:

    var text = "ABCDEFGH";
    for (var i=0; i< text.length; i++){
    	console.log(text[i] ,text.charCodeAt(i))
    }

    It's obvious that this method is not going to be used for obtaining key codes of shif, ctrl or Alt key in keyboard, if you need them stick with the method stated above which uses keypress event.

    FYI, to convert keyCode to Char: String.fromCharCode(65) returns A.

    0 讨论(0)
  • 2020-12-28 10:21

    The bottom of http://www.quirksmode.org/js/keys.html can show the keycode of keys you have pressed for the selected keyboard events.

    0 讨论(0)
  • 2020-12-28 10:23

    Try not to hard-code too many keycodes. Let the JS library convert them for you wherever possible:

    var code = ev.keyCode,
        ascii = String.fromCharCode(code);
    alert(ascii);
    
    0 讨论(0)
  • 2020-12-28 10:25

    As in, what keyboard events reports based on what keys are pressed

      $("#textinput").keydown(function(e) {
        e.keyCode; // this value
      });
    

    Try Here for all the key Events and These are the mobile key Events

    0 讨论(0)
  • 2020-12-28 10:29

    Vanilla javascript + Alert:

    document.addEventListener('keypress', function(e) {
      alert("Key: " + e.code + ", Code: " + e.charCode)
    });
    

    Vanilla javascript + console:

    document.addEventListener('keypress', function(e) {
      console.log("Key: " + e.code + ", Code: " + e.charCode)
    });
    
    0 讨论(0)
提交回复
热议问题