keycode和charcode [英] keycode and charcode
问题描述
为什么人们会写出像
e.keyCode ? e.keyCode : e.charCode
有些人还使用 e.which
有人可以解释一下吗?
推荐答案
始终如一地处理关键事件并不容易。
Handling key events consistently is not at all easy.
首先,有两种不同类型的代码:键盘代码(代表用户按下的键盘上的键的数字) )和字符代码(表示Unicode字符的数字)。您只能在 keypress
事件中可靠地获取字符代码。不要尝试获取 keyup
和 keydown
事件的字符代码。
Firstly, there are two different types of codes: keyboard codes (a number representing the key on the keyboard the user pressed) and character codes (a number representing a Unicode character). You can only reliably get character codes in the keypress
event. Do not try to get character codes for keyup
and keydown
events.
其次,您在 keypress
事件中获得的值与 keyup
中获得的值不同,或者 keydown
event。
Secondly, you get different sets of values in a keypress
event to what you get in a keyup
or keydown
event.
我建议此页面作为有用的资源。总结:
I recommend this page as a useful resource. As a summary:
如果您对检测用户输入字符感兴趣,请使用 keypress
事件。 IE奇怪地只将字符代码存储在 keyCode
中,而所有其他浏览器将其存储在中
。一些(但不是全部)浏览器还将其存储在 charCode
和/或 keyCode
中。一个示例按键处理程序:
If you're interested in detecting a user typing a character, use the keypress
event. IE bizarrely only stores the character code in keyCode
while all other browsers store it in which
. Some (but not all) browsers also store it in charCode
and/or keyCode
. An example keypress handler:
function(evt) {
evt = evt || window.event;
var charCode = evt.which || evt.keyCode;
var charStr = String.fromCharCode(charCode);
alert(charStr);
}
如果您对检测不可打印的密钥感兴趣(例如光标键),使用 keydown
事件。这里 keyCode
始终是要使用的属性。请注意, keyup
事件具有相同的属性。
If you're interested in detecting a non-printable key (such as a cursor key), use the keydown
event. Here keyCode
is always the property to use. Note that keyup
events have the same properties.
function(evt) {
evt = evt || window.event;
var keyCode = evt.keyCode;
// Check for left arrow key
if (keyCode == 37) {
alert("Left arrow");
}
}
这篇关于keycode和charcode的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!