键向下键码不返回预期的字符串值 [英] Key down keycode not return expected string value
问题描述
我在我的应用程序中使用了 iframe
。当我按下键盘上的任意键时,我有返回字符串值。
I have using iframe
in my application. I have return string value when i press any key from keyboard.
除键 219,220,221
外,所有其他键都返回预期的字符串值。
All other keys are returned expected string value except key 219 ,220, 221
.
这些键返回Û,Û,Ý
这些值。
但我希望[,],\
这些字符串值。
But i'm expected "[", "]", "\"
these string values.
如何从这些键中获取正确的字符?
How can I get the correct character from those keys?
推荐答案
keydown
和 keyup
根据您的输入键盘类型使用不同键盘的键码(不同的键盘)区域等。)
keydown
and keyup
use keycodes that can vary from keyboard to keyboard depending on your input keyboard type (different keyboards for different regions, etc.).
对于可打印字符,您需要等待浏览器发出 keypress
,为你提供了翻译的字符键的值(如果有的话),它在 charCode
中给你(虽然我很乐意做偏执 e.charCode || e.which
;也许这很傻)。例如,我的键盘上有一个键,在* nix下我配置它的方式是 keydown
/ keyup
并生成字符£
。但是在运行具有不同键盘布局的Windows的虚拟机中,相同的键是 keydown
/ keyup
的键码220但是生成字符#
。
For printable characters, you need to wait for the browser to issue keypress
, which gives you the translated value of the key to character (if there is one), which it gives you in charCode
(although paranoically I tend to do e.charCode || e.which
; maybe that's silly). For instance, there's a key on my keyboard that, under *nix the way I have it configured, is keycode 220 for keydown
/keyup
and generates the character £
. But in a virtual machine running Windows with a different keyboard layout, that same key is keycode 220 for keydown
/keyup
but generates the character #
.
示例:
function handler(e) {
var msg = "Received " + e.type;
if (e.type === "keypress") {
// keypress
msg += " '" + String.fromCharCode(e.charCode || e.which) + "'";
} else {
// keydown/keyup
msg += " " + (e.which || e.keyCode);
}
console.log(msg);
}
document.addEventListener("keydown", handler, false);
document.addEventListener("keyup", handler, false);
document.addEventListener("keypress", handler, false);
Click here to focus the document, then press keys.
这篇关于键向下键码不返回预期的字符串值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!