问题
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