Key code for common characters on international keyboards

只谈情不闲聊 提交于 2019-12-22 19:47:30

问题


Ok, capturing key codes from special symbols produces different results on keyboards with different layouts. But how about the 'common' characters, like a-z? If you have a QWERTY-keyboard, you'd get key code 81 when you type q. When you have an AZERTY-keyboard, do you get code 81 when you press a, since a is where q 'should' be? Or is the mapping done differently?

EDIT:

The answer I accepted is probably the best solution when you're capturing keys and want to be sure 'a' is really 'a', but as I explain in the comment underneath that, I still am curious how the key codes are 'translated' when using int'l keyboards. That is: sources suggest at least a-z should be consistent, but I cannot find support for this (or someone who actually tried).


回答1:


If you use the keypress event rather than keyup or keydown then the problem goes away because in that event you get character codes rather than key codes.

Example:

document.onkeypress = function(e) {
    e = e || window.event;
    var charCode = (typeof e.which == "undefined") ? e.keyCode : e.which;
    alert( String.fromCharCode(charCode) );
};

And here's the definitive resource on key handling in JavaScript: http://unixpapa.com/js/key.html



来源:https://stackoverflow.com/questions/10531977/key-code-for-common-characters-on-international-keyboards

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