Javascript Keycode for a: 65 or 97?

扶醉桌前 提交于 2021-02-16 05:11:27

问题


I'm working with javascript (on a macbook pro OSX 10.11.x, not sure if this matters) using Chrome browser. Im using the function:

window.onkeypress = function(e) {
    var key = e.keyCode ? e.keyCode : e.which;
    console.log("keypressed = " + key);
}

when i press 'a' key on my keyboard, it logs as 97, however this does not correspond to any other keyCode list i find on the internet, which states 'a' is 65.

This is the same for other keys as well, for example, 's' for me is 115, but everyone else states that 's' is 83.

Is there a dependency that i'm missing? If i fire an event assuming a == 95, will it work on other browsers?

Thanks.


回答1:


So I found that a capital A is indeed, 65.

A lowercase a is 97

Please see this chart:

Chart original location: http://www.asciitable.com/




回答2:


Capital letters are not the same as lower-case and produce different codes.

Also, the keypress event works differently than the keyup or keydown events. keypress responds to printable characters and gives the code of the character that was produced. With keyup and keydown, the code represents the physical hardware key on the keyboard that was pressed. For example, if you run the snippet below and just press the SHIFT key, you will not see the keypress event log message at all because that event doesn't fire for that key.

window.addEventListener("keyup", function(e) {
    var key = e.keyCode ? e.keyCode : e.which;
    console.log("key up = " + key, e.key);
});

window.addEventListener("keydown", function(e) {
    var key = e.keyCode ? e.keyCode : e.which;
    console.log("key down = " + key, e.key);
});

window.addEventListener("keypress", function(e) {
    var key = e.keyCode ? e.keyCode : e.which;
    console.log("key pressed = " + key, e.key);
});
Just click in this area to give it the focus, then press some keys.


来源:https://stackoverflow.com/questions/45361026/javascript-keycode-for-a-65-or-97

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!