简体   繁体   English

从 JavaScript 中的 KeyCode 获取字符值……然后修剪

[英]Get Character value from KeyCode in JavaScript… then trim

This is what I have now:这就是我现在所拥有的:

$("input").bind("keydown",function(e){
    var value = this.value + String.fromCharCode(e.keyCode);
}

If the e.keyCode may not be an ASCII character ( Alt , backspace , del , arrows , etc.)... I would now need to trim these values from value somehow (preferably programmatically - not with lookup tables).如果e.keyCode可能不是 ASCII 字符( Altbackspacedelarrows等)...我现在需要以某种方式从value trim这些值(最好以编程方式 - 而不是使用查找表)。

I'm using jQuery.我正在使用 jQuery。

I must use the keydown event.我必须使用keydown事件。 keyPress doesn't activate for certain keys I need to capture ( Esc , del , backspace , etc.).对于我需要捕获的某些键( Escdelbackspace等), keyPress不会激活。

I cannot use setTimeout to get the input's value.我不能使用setTimeout来获取输入的值。 setTimeout(function(){},0) is too slow. setTimeout(function(){},0)太慢了。

In my experience String.fromCharCode(e.keyCode) is unreliable.根据我的经验String.fromCharCode(e.keyCode)是不可靠的。 String.fromCharCode expects unicode charcodes as an argument; String.fromCharCode需要 unicode 字符码作为参数; e.keyCode returns javascript keycodes. e.keyCode返回 javascript 键码。 Javascript keycodes and unicode charcodes are not the same thing! Javascript 键码和 unicode 字符码不是一回事! In particular, the numberpad keys return a different keycode from the ordinary number keys (since they are different keys) while the same keycode is returned for both upper and lowercase letters (you pressed the same key in both cases), despite them having different charcodes .特别是,数字键盘键返回与普通数字键不同的keycode (因为它们是不同的键),而upperlowercase字母返回相同的keycode (您在两种情况下都按下了相同的键),尽管它们具有不同的charcodes .

For example, the ordinary number key 1 generates an event with keycode 49 while numberpad key 1 (with Numlock on) generates keycode 97. Used with String.fromCharCode we get the following:例如,普通数字键 1 生成keycode 49 的事件,而数字键盘键 1(启用Numlock )生成keycode 97。与String.fromCharCode使用,我们得到以下结果:

String.fromCharCode(49) returns "1"
String.fromCharCode(97) returns "a"

String.fromCharCode expects unicode charcodes, not javascript keycodes. String.fromCharCode需要 unicode 字符码,而不是 javascript 键码。 The key a generates an event with a keycode of 65, independentant of the case of the character it would generate (there is also a modifier for if the Shift key is pressed, etc. in the event).a生成一个keycode为 65 的事件,与它将生成的字符的大小写无关(如果在事件中按下Shift键等,还有一个修饰符)。 The character a has a unicode charcode of 61 while the character A has a charcode of 41 (according to, for example, http://www.utf8-chartable.de/ ).人物A有一个unicode charcode 61而字符A具有charcode的41(根据,例如, http://www.utf8-chartable.de/ )。 However, those are hex values, converting to decimal gives us a charcode of 65 for "A" and 97 for "a".[1]但是,这些是hex值,转换为十进制后,我们得到的charcode为“A”为 65,“a”为 97。 [1] This is consistent with what we get from String.fromCharCode for these values.这与我们从String.fromCharCode获得的这些值是一致的。

My own requirement was limited to processing numbers and ordinary letters (accepting or rejecting depending on the position in the string) and letting control characters ( F -keys, Ctrl -something) through.我自己的要求仅限于处理数字和普通字母(接受或拒绝取决于字符串中的位置)并让控制字符( F键、 Ctrl某些东西)通过。 Thus I can check for the control characters, if it's not a control character I check against a range and only then do I need to get the actual character.因此,我可以检查控制字符,如果它不是控制字符,我会根据范围进行检查,然后才需要获取实际字符。 Given I'm not worried about case (I change all letters to uppercase anyway) and have already limited the range of keycodes, I only have to worry about the numberpad keys.鉴于我不担心大小写(无论如何我都将所有字母更改为大写)并且已经限制了键码的范围,我只需要担心数字键盘键。 The following suffices for that:以下就足够了:

String.fromCharCode((96 <= key && key <= 105)? key-48 : key)

More generally, a function to reliably return the character from a charcode would be great (maybe as a jQuery plugin), but I don't have time to write it just now.更一般地说,从字符代码可靠地返回字符的charcode会很棒(也许作为 jQuery 插件),但我现在没有时间编写它。 Sorry.对不起。

I'd also mention e.which (if you're using jQuery) which normalizes e.keyCode and e.charCode , so that you don't need to worry about what sort of key was pressed.我还提到了e.which (如果您使用的是 jQuery), e.keyCodee.charCode标准化,这样您就不必担心按下了哪种键。 The problem with combining it with String.fromCharCode remains.将它与String.fromCharCode结合的问题仍然存在。

[1] I was confused for a while -. [1] 我一时糊涂了-。 all the docs say that String.fromCharCode expects a unicode charcode , while in practice it seemed to work for ASCII charcodes, but that was I think due to the need to convert to decimal from hex, combined with the fact that ASCII charcodes and unicode decimal charcodes overlap for ordinary latin letters.所有的文档都说String.fromCharCode需要一个 unicode charcode ,而在实践中它似乎适用于 ASCII 字符码,但我认为这是因为需要从十六进制转换为十进制,再加上 ASCII 字符码和 Unicode 十进制数普通拉丁字母的字符代码重叠。

Maybe I didn't understand the question correctly, but can you not use keyup if you want to capture both inputs?也许我没有正确理解这个问题,但是如果您想捕获两个输入,您可以不使用keyup吗?

$("input").bind("keyup",function(e){
    var value = this.value + String.fromCharCode(e.keyCode);
});

Readable key names indexed by key code由键码索引的可读键名

There are relatively few key codes so I simply listed all the corresponding values in a static array so I could simply convert the number 65 into A using keyboardMap[65]键码相对较少,所以我只是在静态数组中列出了所有相应的值,这样我就可以使用keyboardMap[65]将数字65简单地转换为A

Not all key codes map to a printable character so some other identifiable string is returned.并非所有键码都映射到可打印字符,因此会返回一些其他可识别的字符串。

You may need to modify the array to suit your needs and can simply return empty strings for all the characters you don't care to translate.您可能需要修改数组以满足您的需要,并且可以简单地为您不想翻译的所有字符返回空字符串。 The following array allows me to quickly and reliably determine which key was pressed in any environment.以下数组使我能够快速可靠地确定在任何环境中按下了哪个键。 Enjoy!享受!

// names of known key codes (0-255)

var keyboardMap = [
  "", // [0]
  "", // [1]
  "", // [2]
  "CANCEL", // [3]
  "", // [4]
  "", // [5]
  "HELP", // [6]
  "", // [7]
  "BACK_SPACE", // [8]
  "TAB", // [9]
  "", // [10]
  "", // [11]
  "CLEAR", // [12]
  "ENTER", // [13]
  "ENTER_SPECIAL", // [14]
  "", // [15]
  "SHIFT", // [16]
  "CONTROL", // [17]
  "ALT", // [18]
  "PAUSE", // [19]
  "CAPS_LOCK", // [20]
  "KANA", // [21]
  "EISU", // [22]
  "JUNJA", // [23]
  "FINAL", // [24]
  "HANJA", // [25]
  "", // [26]
  "ESCAPE", // [27]
  "CONVERT", // [28]
  "NONCONVERT", // [29]
  "ACCEPT", // [30]
  "MODECHANGE", // [31]
  "SPACE", // [32]
  "PAGE_UP", // [33]
  "PAGE_DOWN", // [34]
  "END", // [35]
  "HOME", // [36]
  "LEFT", // [37]
  "UP", // [38]
  "RIGHT", // [39]
  "DOWN", // [40]
  "SELECT", // [41]
  "PRINT", // [42]
  "EXECUTE", // [43]
  "PRINTSCREEN", // [44]
  "INSERT", // [45]
  "DELETE", // [46]
  "", // [47]
  "0", // [48]
  "1", // [49]
  "2", // [50]
  "3", // [51]
  "4", // [52]
  "5", // [53]
  "6", // [54]
  "7", // [55]
  "8", // [56]
  "9", // [57]
  "COLON", // [58]
  "SEMICOLON", // [59]
  "LESS_THAN", // [60]
  "EQUALS", // [61]
  "GREATER_THAN", // [62]
  "QUESTION_MARK", // [63]
  "AT", // [64]
  "A", // [65]
  "B", // [66]
  "C", // [67]
  "D", // [68]
  "E", // [69]
  "F", // [70]
  "G", // [71]
  "H", // [72]
  "I", // [73]
  "J", // [74]
  "K", // [75]
  "L", // [76]
  "M", // [77]
  "N", // [78]
  "O", // [79]
  "P", // [80]
  "Q", // [81]
  "R", // [82]
  "S", // [83]
  "T", // [84]
  "U", // [85]
  "V", // [86]
  "W", // [87]
  "X", // [88]
  "Y", // [89]
  "Z", // [90]
  "OS_KEY", // [91] Windows Key (Windows) or Command Key (Mac)
  "", // [92]
  "CONTEXT_MENU", // [93]
  "", // [94]
  "SLEEP", // [95]
  "NUMPAD0", // [96]
  "NUMPAD1", // [97]
  "NUMPAD2", // [98]
  "NUMPAD3", // [99]
  "NUMPAD4", // [100]
  "NUMPAD5", // [101]
  "NUMPAD6", // [102]
  "NUMPAD7", // [103]
  "NUMPAD8", // [104]
  "NUMPAD9", // [105]
  "MULTIPLY", // [106]
  "ADD", // [107]
  "SEPARATOR", // [108]
  "SUBTRACT", // [109]
  "DECIMAL", // [110]
  "DIVIDE", // [111]
  "F1", // [112]
  "F2", // [113]
  "F3", // [114]
  "F4", // [115]
  "F5", // [116]
  "F6", // [117]
  "F7", // [118]
  "F8", // [119]
  "F9", // [120]
  "F10", // [121]
  "F11", // [122]
  "F12", // [123]
  "F13", // [124]
  "F14", // [125]
  "F15", // [126]
  "F16", // [127]
  "F17", // [128]
  "F18", // [129]
  "F19", // [130]
  "F20", // [131]
  "F21", // [132]
  "F22", // [133]
  "F23", // [134]
  "F24", // [135]
  "", // [136]
  "", // [137]
  "", // [138]
  "", // [139]
  "", // [140]
  "", // [141]
  "", // [142]
  "", // [143]
  "NUM_LOCK", // [144]
  "SCROLL_LOCK", // [145]
  "WIN_OEM_FJ_JISHO", // [146]
  "WIN_OEM_FJ_MASSHOU", // [147]
  "WIN_OEM_FJ_TOUROKU", // [148]
  "WIN_OEM_FJ_LOYA", // [149]
  "WIN_OEM_FJ_ROYA", // [150]
  "", // [151]
  "", // [152]
  "", // [153]
  "", // [154]
  "", // [155]
  "", // [156]
  "", // [157]
  "", // [158]
  "", // [159]
  "CIRCUMFLEX", // [160]
  "EXCLAMATION", // [161]
  "DOUBLE_QUOTE", // [162]
  "HASH", // [163]
  "DOLLAR", // [164]
  "PERCENT", // [165]
  "AMPERSAND", // [166]
  "UNDERSCORE", // [167]
  "OPEN_PAREN", // [168]
  "CLOSE_PAREN", // [169]
  "ASTERISK", // [170]
  "PLUS", // [171]
  "PIPE", // [172]
  "HYPHEN_MINUS", // [173]
  "OPEN_CURLY_BRACKET", // [174]
  "CLOSE_CURLY_BRACKET", // [175]
  "TILDE", // [176]
  "", // [177]
  "", // [178]
  "", // [179]
  "", // [180]
  "VOLUME_MUTE", // [181]
  "VOLUME_DOWN", // [182]
  "VOLUME_UP", // [183]
  "", // [184]
  "", // [185]
  "SEMICOLON", // [186]
  "EQUALS", // [187]
  "COMMA", // [188]
  "MINUS", // [189]
  "PERIOD", // [190]
  "SLASH", // [191]
  "BACK_QUOTE", // [192]
  "", // [193]
  "", // [194]
  "", // [195]
  "", // [196]
  "", // [197]
  "", // [198]
  "", // [199]
  "", // [200]
  "", // [201]
  "", // [202]
  "", // [203]
  "", // [204]
  "", // [205]
  "", // [206]
  "", // [207]
  "", // [208]
  "", // [209]
  "", // [210]
  "", // [211]
  "", // [212]
  "", // [213]
  "", // [214]
  "", // [215]
  "", // [216]
  "", // [217]
  "", // [218]
  "OPEN_BRACKET", // [219]
  "BACK_SLASH", // [220]
  "CLOSE_BRACKET", // [221]
  "QUOTE", // [222]
  "", // [223]
  "META", // [224]
  "ALTGR", // [225]
  "", // [226]
  "WIN_ICO_HELP", // [227]
  "WIN_ICO_00", // [228]
  "", // [229]
  "WIN_ICO_CLEAR", // [230]
  "", // [231]
  "", // [232]
  "WIN_OEM_RESET", // [233]
  "WIN_OEM_JUMP", // [234]
  "WIN_OEM_PA1", // [235]
  "WIN_OEM_PA2", // [236]
  "WIN_OEM_PA3", // [237]
  "WIN_OEM_WSCTRL", // [238]
  "WIN_OEM_CUSEL", // [239]
  "WIN_OEM_ATTN", // [240]
  "WIN_OEM_FINISH", // [241]
  "WIN_OEM_COPY", // [242]
  "WIN_OEM_AUTO", // [243]
  "WIN_OEM_ENLW", // [244]
  "WIN_OEM_BACKTAB", // [245]
  "ATTN", // [246]
  "CRSEL", // [247]
  "EXSEL", // [248]
  "EREOF", // [249]
  "PLAY", // [250]
  "ZOOM", // [251]
  "", // [252]
  "PA1", // [253]
  "WIN_OEM_CLEAR", // [254]
  "" // [255]
];

Note: The position of each value in the array above is important.注意:上面数组中每个值的位置很重要。 The "" are placeholders for codes with unknown values. ""是具有未知值的代码的占位符。

Try the following code snippet using this static array lookup approach...使用此静态数组查找方法尝试以下代码片段...

 var keyCodes = []; $("#reset").click(function() { keyCodes = []; $("#in").val(""); $("#key-codes").html("var keyCodes = [ ];"); $("#key-names").html("var keyNames = [ ];"); }); $(document).keydown(function(e) { keyCodes.push(e.which); updateOutput(); }); function updateOutput() { var kC = "var keyCodes = [ "; var kN = "var keyNames = [ "; var len = keyCodes.length; for (var i = 0; i < len; i++) { kC += keyCodes[i]; kN += "'"+keyboardMap[keyCodes[i]]+"'"; if (i !== (len - 1)) { kC += ", "; kN += ", "; } } kC += " ];"; kN += " ];"; $("#key-codes").html(kC); $("#key-names").html(kN); } var keyboardMap = [ "", // [0] "", // [1] "", // [2] "CANCEL", // [3] "", // [4] "", // [5] "HELP", // [6] "", // [7] "BACK_SPACE", // [8] "TAB", // [9] "", // [10] "", // [11] "CLEAR", // [12] "ENTER", // [13] "ENTER_SPECIAL", // [14] "", // [15] "SHIFT", // [16] "CONTROL", // [17] "ALT", // [18] "PAUSE", // [19] "CAPS_LOCK", // [20] "KANA", // [21] "EISU", // [22] "JUNJA", // [23] "FINAL", // [24] "HANJA", // [25] "", // [26] "ESCAPE", // [27] "CONVERT", // [28] "NONCONVERT", // [29] "ACCEPT", // [30] "MODECHANGE", // [31] "SPACE", // [32] "PAGE_UP", // [33] "PAGE_DOWN", // [34] "END", // [35] "HOME", // [36] "LEFT", // [37] "UP", // [38] "RIGHT", // [39] "DOWN", // [40] "SELECT", // [41] "PRINT", // [42] "EXECUTE", // [43] "PRINTSCREEN", // [44] "INSERT", // [45] "DELETE", // [46] "", // [47] "0", // [48] "1", // [49] "2", // [50] "3", // [51] "4", // [52] "5", // [53] "6", // [54] "7", // [55] "8", // [56] "9", // [57] "COLON", // [58] "SEMICOLON", // [59] "LESS_THAN", // [60] "EQUALS", // [61] "GREATER_THAN", // [62] "QUESTION_MARK", // [63] "AT", // [64] "A", // [65] "B", // [66] "C", // [67] "D", // [68] "E", // [69] "F", // [70] "G", // [71] "H", // [72] "I", // [73] "J", // [74] "K", // [75] "L", // [76] "M", // [77] "N", // [78] "O", // [79] "P", // [80] "Q", // [81] "R", // [82] "S", // [83] "T", // [84] "U", // [85] "V", // [86] "W", // [87] "X", // [88] "Y", // [89] "Z", // [90] "OS_KEY", // [91] Windows Key (Windows) or Command Key (Mac) "", // [92] "CONTEXT_MENU", // [93] "", // [94] "SLEEP", // [95] "NUMPAD0", // [96] "NUMPAD1", // [97] "NUMPAD2", // [98] "NUMPAD3", // [99] "NUMPAD4", // [100] "NUMPAD5", // [101] "NUMPAD6", // [102] "NUMPAD7", // [103] "NUMPAD8", // [104] "NUMPAD9", // [105] "MULTIPLY", // [106] "ADD", // [107] "SEPARATOR", // [108] "SUBTRACT", // [109] "DECIMAL", // [110] "DIVIDE", // [111] "F1", // [112] "F2", // [113] "F3", // [114] "F4", // [115] "F5", // [116] "F6", // [117] "F7", // [118] "F8", // [119] "F9", // [120] "F10", // [121] "F11", // [122] "F12", // [123] "F13", // [124] "F14", // [125] "F15", // [126] "F16", // [127] "F17", // [128] "F18", // [129] "F19", // [130] "F20", // [131] "F21", // [132] "F22", // [133] "F23", // [134] "F24", // [135] "", // [136] "", // [137] "", // [138] "", // [139] "", // [140] "", // [141] "", // [142] "", // [143] "NUM_LOCK", // [144] "SCROLL_LOCK", // [145] "WIN_OEM_FJ_JISHO", // [146] "WIN_OEM_FJ_MASSHOU", // [147] "WIN_OEM_FJ_TOUROKU", // [148] "WIN_OEM_FJ_LOYA", // [149] "WIN_OEM_FJ_ROYA", // [150] "", // [151] "", // [152] "", // [153] "", // [154] "", // [155] "", // [156] "", // [157] "", // [158] "", // [159] "CIRCUMFLEX", // [160] "EXCLAMATION", // [161] "DOUBLE_QUOTE", // [162] "HASH", // [163] "DOLLAR", // [164] "PERCENT", // [165] "AMPERSAND", // [166] "UNDERSCORE", // [167] "OPEN_PAREN", // [168] "CLOSE_PAREN", // [169] "ASTERISK", // [170] "PLUS", // [171] "PIPE", // [172] "HYPHEN_MINUS", // [173] "OPEN_CURLY_BRACKET", // [174] "CLOSE_CURLY_BRACKET", // [175] "TILDE", // [176] "", // [177] "", // [178] "", // [179] "", // [180] "VOLUME_MUTE", // [181] "VOLUME_DOWN", // [182] "VOLUME_UP", // [183] "", // [184] "", // [185] "SEMICOLON", // [186] "EQUALS", // [187] "COMMA", // [188] "MINUS", // [189] "PERIOD", // [190] "SLASH", // [191] "BACK_QUOTE", // [192] "", // [193] "", // [194] "", // [195] "", // [196] "", // [197] "", // [198] "", // [199] "", // [200] "", // [201] "", // [202] "", // [203] "", // [204] "", // [205] "", // [206] "", // [207] "", // [208] "", // [209] "", // [210] "", // [211] "", // [212] "", // [213] "", // [214] "", // [215] "", // [216] "", // [217] "", // [218] "OPEN_BRACKET", // [219] "BACK_SLASH", // [220] "CLOSE_BRACKET", // [221] "QUOTE", // [222] "", // [223] "META", // [224] "ALTGR", // [225] "", // [226] "WIN_ICO_HELP", // [227] "WIN_ICO_00", // [228] "", // [229] "WIN_ICO_CLEAR", // [230] "", // [231] "", // [232] "WIN_OEM_RESET", // [233] "WIN_OEM_JUMP", // [234] "WIN_OEM_PA1", // [235] "WIN_OEM_PA2", // [236] "WIN_OEM_PA3", // [237] "WIN_OEM_WSCTRL", // [238] "WIN_OEM_CUSEL", // [239] "WIN_OEM_ATTN", // [240] "WIN_OEM_FINISH", // [241] "WIN_OEM_COPY", // [242] "WIN_OEM_AUTO", // [243] "WIN_OEM_ENLW", // [244] "WIN_OEM_BACKTAB", // [245] "ATTN", // [246] "CRSEL", // [247] "EXSEL", // [248] "EREOF", // [249] "PLAY", // [250] "ZOOM", // [251] "", // [252] "PA1", // [253] "WIN_OEM_CLEAR", // [254] "" // [255] ];
 #key-codes, #key-names { font-family: courier, serif; font-size: 1.2em; }
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <input id="in" placeholder="Type here..." /> <button id="reset">Reset</button> <br/> <br/> <div id="key-codes">var keyCodes = [ ];</div> <div id="key-names">var keyNames = [ ];</div>


Key codes worth noting值得注意的关键代码

Letters AZ: (65-90)字母 AZ: (65-90)

keyboardMap[65];  // A
...
keyboardMap[90];  // Z

Digits 0-9: (48-57)数字 0-9: (48-57)

keyboardMap[48];  // 0
...
keyboardMap[57];  // 9

Number Pad 0-9: (96-105)数字键盘 0-9: (96-105)

keyboardMap[96];   // NUMPAD0
...
keyboardMap[105];  // NUMPAD9

Arrow Keys: (37-40)方向键: (37-40)

keyboardMap[37];  // LEFT
keyboardMap[38];  // UP
keyboardMap[39];  // RIGHT
keyboardMap[40];  // DOWN

Tab Key: (9)标签键: (9)

keyboardMap[9];  // TAB

Enter Key: (13)输入键: (13)

keyboardMap[13];  // ENTER

Spacebar Key: (32)空格键: (32)

keyboardMap[32];  // SPACE

OS Specific Key (91) Windows Key (Windows) or Command Key (Mac)操作系统特定键(91) Windows 键 (Windows) 或命令键 (Mac)

keyboardMap[91];  // OS_KEY

Alt Key: (18) Alt键: (18)

keyboardMap[18];  // ALT

Control Key: (17)控制键: (17)

keyboardMap[17];  // CONTROL

Shift Key: (16) Shift 键: (16)

keyboardMap[16];  // SHIFT

Caps Lock Key: (20) Caps Lock 键: (20)

keyboardMap[20];  // CAPS_LOCK

Just an important note: the accepted answer above will not work correctly for keyCode >= 144, ie period, comma, dash, etc. For those you should use a more general algorithm:只是一个重要的注意事项:上面接受的答案不适用于 keyCode >= 144,即句点、逗号、破折号等。对于那些你应该使用更通用的算法:

let chrCode = keyCode - 48 * Math.floor(keyCode / 48);
let chr = String.fromCharCode((96 <= keyCode) ? chrCode: keyCode);

If you're curious as to why, this is apparently necessary because of the behavior of the built-in JS function String.fromCharCode() .如果您想知道为什么,这显然是必要的,因为内置 JS 函数String.fromCharCode() For values of keyCode <= 96 it seems to map using the function:对于keyCode <= 96值,它似乎使用以下函数进行映射:

chrCode = keyCode - 48 * Math.floor(keyCode / 48)

For values of keyCode > 96 it seems to map using the function:对于keyCode > 96值,它似乎使用以下函数进行映射:

chrCode = keyCode

If this seems like odd behavior then well..I agree.如果这看起来很奇怪,那么好吧..我同意。 Sadly enough, it would be very far from the weirdest thing I've seen in the JS core.可悲的是,这与我在 JS 核心中看到的最奇怪的事情相去甚远。

 document.onkeydown = function(e) { let keyCode = e.keyCode; let chrCode = keyCode - 48 * Math.floor(keyCode / 48); let chr = String.fromCharCode((96 <= keyCode) ? chrCode: keyCode); console.log(chr); };
 <input type="text" placeholder="Focus and Type"/>

I'm assuming this is for a game or for a fast-responding type of application hence the use of KEYDOWN than KEYPRESS.我假设这是用于游戏或快速响应类型的应用程序,因此使用 KEYDOWN 而不是 KEYPRESS。

Edit : Dang!编辑:当! I stand corrected (thank you Crescent Fresh and David): JQuery (or even rather the underlying DOM hosts) do not expose the detail of the WM_KEYDOWN and of other events.我更正了(感谢 Crescent Fresh 和 David):JQuery(或者甚至是底层 DOM 主机)没有公开 WM_KEYDOWN 和其他事件的细节。 Rather they pre-digest this data and, in the case of keyDown even in JQuery, we get:相反,他们预先消化了这些数据,在 keyDown 的情况下,甚至在 JQuery 中,我们得到:

Note that these properties are the UniCode values.请注意,这些属性是 UniCode 值。
Note, I wasn't able to find an authorititative reference to that in JQuery docs, but many reputable examples on the net refer to these two properties.请注意,我无法在 JQuery 文档中找到对此的权威参考,但是网络上的许多著名示例都引用了这两个属性。

The following code, adapted from some java (not javascript) of mine, is therefore totally wrong...以下代码改编自我的一些 java(不是 javascript),因此完全错误......

The following will give you the "interesting" parts of the keycode:以下将为您提供密钥代码的“有趣”部分:

  value = e.KeyCode;
  repeatCount = value & 0xFF;
  scanCode = (value >> 16) & 0xFF;  // note we take the "extended bit" deal w/ it later.
  wasDown = ((value & 0x4000) != 0);  // indicate key was readily down (auto-repeat)
  if (scanCode > 127)
      // deal with extended
  else
      // "regular" character

You can also use the read-only property key .您还可以使用只读属性key It also respects special keys like shift etc. and is supported by IE9.它还尊重特殊键,如shift等,并受 IE9 支持。

When a non-printable or special character is pressed, the value will be on of the defined key values like 'Shift' or 'Multiply' .当按下不可打印或特殊字符时,该值将位于定义的键值中,例如'Shift''Multiply'

  • Keyboard event.key键盘事件event.key
  • X -> 'x' X -> 'x'
  • Shift + X -> 'X' Shift + X -> 'X'
  • F5 -> 'F5' F5 -> 'F5'

I know this is an old question, but I came across it today searching for a pre-packaged solution to this problem, and found nothing that really met my needs.我知道这是一个老问题,但我今天遇到了这个问题,正在寻找针对此问题的预打包解决方案,但没有找到真正满足我需求的内容。

Here is a solution (English only) that correctly supports Upper Case (shifted), Lower Case, punctuation, number keypad, etc.这是一个正确支持大写(移位)、小写、标点符号、数字键盘等的解决方案(仅英文)。

It also allows for simple and straight-forward identification of - and reaction to - non-printable keys, like ESC, Arrows, Function keys, etc.它还允许对不可打印的键(如 ESC、箭头、功能键等)进行简单直接的识别和反应。

https://jsfiddle.net/5hhu896g/1/ https://jsfiddle.net/5hhu896g/1/

keyboardCharMap and keyboardNameMap are the key to making this work

Thanks to DaveAlger for saving me some typing - and much discovery!感谢 DaveAlger 帮我节省了一些打字的时间——还有很多发现! - by providing the Named Key Array. - 通过提供命名键数组。

I recently wrote a module called keysight that translates keypress , keydown , and keyup events into characters and keys respectively.我最近写了一个名为模块keysight即转换keypresskeydown ,并keyup成字符和按键事件分别。

Example:例子:

 element.addEventListener("keydown", function(event) {
    var character = keysight(event).char
 })

For those of you who came here looking for the actual Unicode character values for a keycode, like I did, here is a function for that.对于那些来这里寻找键码的实际 Unicode 字符值的人,就像我一样,这里有一个函数。 For instance, given the right arrow unicode keycode this will output the visible string \\[\C例如,给定向右箭头 unicode 键码,这将输出可见字符串\\[\C

function toUnicode(theString) {
    var unicodeString = '';
    for (var i = 0; i < theString.length; i++) {
        var theUnicode = theString.charCodeAt(i).toString(16).toUpperCase();
        while (theUnicode.length < 4) {
            theUnicode = '0' + theUnicode;
        }
        theUnicode = '\\u' + theUnicode;
        unicodeString += theUnicode;
    }
    return unicodeString;
}

Refer this link Get Keycode from key press and char value for any key code请参阅此链接从按键中获取键码和任何键码的字符值

$('input#inp').keyup(function(e){
   $(this).val(String.fromCharCode(e.keyCode)); 
   $('div#output').html('Keycode : ' + e.keyCode);  
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM