JavaScript KeyCode与CharCode [英] JavaScript KeyCode vs CharCode
问题描述
问题:
- 将HTML输入中允许的字符限制为仅限az AZ。
- 对于业务需求,这需要在KeyPress上完成,以便角色根本不允许出现在输入中。
- Tab,enter,arrows,backspace,shift都是允许的。用户必须能够自由地移入和移出文本框,删除字符等等。
这是我的起点代码...
This is the starting point of my code...
var keyCode = (e.keyCode ? e.keyCode : e.which);
但是我在 keyCode 中获得的每个值都与不对应我在网上看到的任何字符图表。例如,字符h给我一个返回码104.
However every value that I get in keyCode doesnt correspond to any of the character charts I have seen on the web. For example the character "h" gives me a return code of 104.
KeyCode与CharCode不同吗?哪个代码包含控制字符?我需要转换吗?
Is KeyCode different to CharCode? Which code contains the control characters? Do I need to convert?
如何将输入限制为az AZ并允许我在JavaScript中需要的键?
How can I restrict the input to a-z A-Z and allow the keys I need in JavaScript?
推荐答案
您可以在上找到所有问题的答案。以下页面。
...但总结如下:
- 您可以可靠地获取角色信息(而不是密钥代码信息)的唯一事件是
keypress
事件。 - In
keypress
事件,除IE< = 8之外的所有浏览器都将字符代码存储在事件的中
属性中。大多数但不是所有这些浏览器还将字符代码存储在charCode
属性中。 - 在
keypress中
event,IE< = 8将字符代码存储在keyCode
属性中。
- The only event from which you can reliably obtain character information (as opposed to key code information) is the
keypress
event. - In the
keypress
event, all browsers except IE <= 8 store the character code in the event'swhich
property. Most but not all of these browsers also store the character code in thecharCode
property. - In the
keypress
event, IE <= 8 stores the character code in thekeyCode
property.
这意味着要获得与按键相对应的字符代码,假设按键事件对象存储在名为 e $ c $的变量中,以下内容将在任何地方都有效c>:
This means to get the character code corresponding to the keypress, the following will work everywhere, assuming a keypress event object is stored in a variable called e
:
var charCode = (typeof e.which == "number") ? e.which : e.keyCode
这通常会返回一个存在的字符代码,否则为0 。在某些情况下,如果不这样做,您将获得非零值:
This will generally return you a character code where one exists and 0 otherwise. There are a few cases where you'll get a non-zero value when you shouldn't:
- 在Opera< 10.50为键插入,删除,主页和结束
- In最新版本的Konqueror用于非字符键。
- In Opera < 10.50 for keys Insert, Delete, Home and End
- In recent versions of Konqueror for non-character keys.
第一个问题的解决方法有点涉及,需要使用 keydown
事件。
The workaround for the first problem is a little involved and requires using the keydown
event as well.
这篇关于JavaScript KeyCode与CharCode的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!