How to convert a char to its keycode?

前端 未结 5 1363
闹比i
闹比i 2020-12-09 14:26

How can I convert a character to its respective keycode?

For example:

  • a to 65
  • b to 66
5条回答
  •  温柔的废话
    2020-12-09 15:28

    As pointed out in the comments: the accepted answer is not correct, because it gives the character code and not the keyCode, which can be different, e.g. 'a'.charCodeAt(0) == 97 while the correct keyCode is 65.

    for converting just the standard characters from [a-zA-Z] or numbers [0-9] the code below can be used.

    However this does not work correctly for any special keys like ., Ö, # or whatsoever and I did not find a good solution for them. As a workaround one could use a site like http://keycode.info/ (which just captures the onkeydown events and reads the event.keyCode property).

    function convertToKeyCode(target) {
        var keyCode = target.value.toUpperCase().charCodeAt(0);
        document.getElementById("keyCodeSpan").innerHTML = keyCode;
    }
    
    Keycode: 

提交回复
热议问题