从 JavaScript 中的 KeyCode 获取字符值...然后修剪
这就是我现在所拥有的:
$("input").bind("keydown",function(e){
var value = this.value + String.fromCharCode(e.keyCode);
}
如果 e.keyCode
可能不是 ASCII 字符(Alt、backspace、del、箭头等)... 我现在需要以某种方式从 value
中修剪
这些值(最好以编程方式 - 不使用查找表)。
我正在使用 jQuery。
我必须使用 keydown
事件。对于我需要捕获的某些键(Esc、del、backspace 等),keyPress
不会激活。
我无法使用 setTimeout
来获取输入的值。 setTimeout(function(){},0)
太慢了。
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).
I'm using jQuery.
I must use the keydown
event. keyPress
doesn't activate for certain keys I need to capture (Esc, del, backspace, etc.).
I cannot use setTimeout
to get the input's value. setTimeout(function(){},0)
is too slow.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(10)
根据我的经验,
String.fromCharCode(e.keyCode)
是不可靠的。String.fromCharCode
期望 unicode 字符代码作为参数;e.keyCode
返回 javascript 键码。 Javascript 键码和 unicode 字符码不是一回事!特别是,数字键盘键返回与普通数字键不同的keycode
(因为它们是不同的键),而两个upper
返回相同的keycode
code> 和小写
字母(在这两种情况下按了相同的键),尽管它们具有不同的charcode
。例如,普通数字键 1 生成
keycode
49 的事件,而数字键盘键 1(Numlock 打开)生成keycode
97。String.fromCharCode
我们得到以下结果:String.fromCharCode
需要 unicode 字符代码,而不是 javascript 键码。键 a 生成一个keycode
为 65 的事件,与它生成的字符的大小写无关(如果 Shift< /kbd> 键被按下等事件)。字符 a 的 unicodecharcode
为 61,而字符 A 的charcode
为 41(根据,例如,http://www.utf8-chartable.de/)。但是,这些是十六进制
值,转换为十进制后,“A”的charcode
为 65,“a”为 97。[1]这与我们从 String.fromCharCode 获得的这些值一致。我自己的要求仅限于处理数字和普通字母(根据字符串中的位置接受或拒绝)并让控制字符(F-keys,Ctrl-something)通过。因此,我可以检查控制字符,如果它不是控制字符,我会检查范围,然后才需要获取实际字符。鉴于我不担心大小写(无论如何我都将所有字母更改为大写)并且已经限制了键码的范围,我只需要担心数字键盘键。下面的内容就足够了:
更一般地说,一个能够可靠地从
charcode
返回字符的函数会很棒(也许作为 jQuery 插件),但我现在没有时间编写它。对不起。我还要提到
e.which
(如果您使用的是 jQuery),它规范化e.keyCode
和e.charCode
,以便您不需要担心按下了什么样的键。将其与 String.fromCharCode 组合的问题仍然存在。[1]我一时糊涂了——。所有文档都说
String.fromCharCode
需要一个 unicodecharcode
,而实际上它似乎适用于 ASCII 字符代码,但我认为这是因为需要转换为十六进制的十进制,加上普通拉丁字母的 ASCII 字符代码和 unicode 十进制字符代码重叠的事实。In my experience
String.fromCharCode(e.keyCode)
is unreliable.String.fromCharCode
expects unicode charcodes as an argument;e.keyCode
returns javascript keycodes. Javascript keycodes and unicode charcodes are not the same thing! In particular, the numberpad keys return a differentkeycode
from the ordinary number keys (since they are different keys) while the samekeycode
is returned for bothupper
andlowercase
letters (you pressed the same key in both cases), despite them having differentcharcodes
.For example, the ordinary number key 1 generates an event with
keycode
49 while numberpad key 1 (with Numlock on) generateskeycode
97. Used withString.fromCharCode
we get the following:String.fromCharCode
expects unicode charcodes, not javascript keycodes. The key a generates an event with akeycode
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). The character a has a unicodecharcode
of 61 while the character A has acharcode
of 41 (according to, for example, http://www.utf8-chartable.de/). However, those arehex
values, converting to decimal gives us acharcode
of 65 for "A" and 97 for "a".[1] This is consistent with what we get fromString.fromCharCode
for these values.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. 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:
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. Sorry.I'd also mention
e.which
(if you're using jQuery) which normalizese.keyCode
ande.charCode
, so that you don't need to worry about what sort of key was pressed. The problem with combining it withString.fromCharCode
remains.[1] I was confused for a while -. all the docs say that
String.fromCharCode
expects a unicodecharcode
, 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.也许我没有正确理解这个问题,但是如果你想捕获两个输入,你能不使用
keyup
吗?Maybe I didn't understand the question correctly, but can you not use
keyup
if you want to capture both inputs?按键代码索引的可读键名称
键代码相对较少,因此我只是在静态数组中列出了所有相应的值,这样我就可以简单地将数字
65
转换为A
使用keyboardMap[65]
并非所有按键代码都映射到可打印字符,因此会返回一些其他可识别字符串。
您可能需要修改数组以满足您的需求,并且只需返回空字符串代表您不关心翻译的所有字符。以下数组使我能够快速可靠地确定在任何环境下按下了哪个键。享受!
使用此静态数组查找方法尝试以下代码片段...
值得注意的关键代码
字母AZ:(65-90)
数字0-9:(48-57)
数字键盘0-9:( 96-105)
箭头键: (37-40)
Tab 键: (9)
Enter 键: (13)
空格键: (32)
操作系统特定键 (91) Windows 键 (Windows) 或 Command 键 (Mac)
Alt 键: ( 18)
Control 键: (17)
Shift 键: (16)
Caps Lock 键: (20)
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
intoA
usingkeyboardMap[65]
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!
Try the following code snippet using this static array lookup approach...
Key codes worth noting
Letters A-Z: (65-90)
Digits 0-9: (48-57)
Number Pad 0-9: (96-105)
Arrow Keys: (37-40)
Tab Key: (9)
Enter Key: (13)
Spacebar Key: (32)
OS Specific Key (91) Windows Key (Windows) or Command Key (Mac)
Alt Key: (18)
Control Key: (17)
Shift Key: (16)
Caps Lock Key: (20)
只是一个重要的注意事项:上面接受的答案对于 keyCode >= 144(即句点、逗号、破折号等)将无法正常工作。对于那些您应该使用更通用的算法:
如果您好奇为什么,这是由于内置 JS 函数
String.fromCharCode()
的行为,这显然是必要的。对于keyCode <= 96
的值,它似乎使用以下函数进行映射:chrCode = keyCode - 48 * Math.floor(keyCode / 48)
对于
的值密钥代码> 96 似乎使用以下函数进行映射:
chrCode = keyCode
如果这看起来很奇怪,那么好吧..我同意。遗憾的是,这与我在 JS 核心中看到的最奇怪的事情相去甚远。
Just an important note: the accepted answer above will not work correctly for keyCode >= 144, i.e. period, comma, dash, etc. For those you should use a more general algorithm:
If you're curious as to why, this is apparently necessary because of the behavior of the built-in JS function
String.fromCharCode()
. For values ofkeyCode <= 96
it seems to map using the function:chrCode = keyCode - 48 * Math.floor(keyCode / 48)
For values of
keyCode > 96
it seems to map using the function: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.
您还可以使用只读属性
key< /代码>
。它还遵循 shift 等特殊键,并受 IE9 支持。
当按下不可打印或特殊字符时,该值将位于定义的 键值,例如
'Shift'
或'Multiply'
。event.key
'x'
'X'
'F5'
You can also use the read-only property
key
. It also respects special keys like shift etc. and is supported by IE9.When a non-printable or special character is pressed, the value will be on of the defined key values like
'Shift'
or'Multiply'
.event.key
'x'
'X'
'F5'
我假设这是针对游戏或快速响应类型的应用程序,因此使用 KEYDOWN 而不是 KEYPRESS。
编辑:
当当!我的观点是正确的(谢谢 Crescent Fresh 和 David):JQuery(或者甚至底层 DOM 主机)确实不公开 WM_KEYDOWN 和其他事件的详细信息。相反,它们会预先消化这些数据,并且即使在 JQuery 中使用 keyDown 的情况下,我们也会得到:
请注意,这些属性是 Unicode 值。
请注意,我无法在 JQuery 文档中找到对此的权威参考,但网上许多有信誉的示例都引用了这两个属性。
下面的代码改编自我的一些java(不是javascript),因此是完全错误的......
下面将为您提供关键代码的“有趣”部分:
I'm assuming this is for a game or for a fast-responding type of application hence the use of KEYDOWN than 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. Rather they pre-digest this data and, in the case of keyDown even in JQuery, we get:
Note that these properties are the UniCode values.
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.
The following code, adapted from some java (not javascript) of mine, is therefore totally wrong...
The following will give you the "interesting" parts of the keycode:
我知道这是一个老问题,但今天我在寻找该问题的预打包解决方案时遇到了它,但没有找到真正满足我需求的东西。
这是一个解决方案(仅限英文),可以正确支持大写(移位)、小写、标点符号、数字键盘等。
它还允许简单直接地识别不可打印的按键(例如 ESC)并对其做出反应、箭头、功能键等
https://jsfiddle.net/5hhu896g/1/
感谢DaveAlger 为我节省了一些打字时间 - 并带来了很多发现! - 通过提供命名密钥数组。
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.
https://jsfiddle.net/5hhu896g/1/
Thanks to DaveAlger for saving me some typing - and much discovery! - by providing the Named Key Array.
我最近编写了一个名为 keysight 的模块,它可以翻译
keypress
、keydown< /code> 和
keyup
事件分别转换为字符和按键。例子:
I recently wrote a module called keysight that translates
keypress
,keydown
, andkeyup
events into characters and keys respectively.Example:
对于那些像我一样来这里寻找键码的实际 Unicode 字符值的人,这里有一个函数。例如,给定右箭头 unicode keycode,这将输出可见字符串
\u001B\u005B\u0043
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. For instance, given the right arrow unicode keycode this will output the visible string
\u001B\u005B\u0043
参考这个链接
从按键中获取键码以及任何键码的字符值
Refer this link
Get Keycode from key press and char value for any key code