keypress,keyup中keyCode不一样

  keypress,keyup/keydown事件中,事件对象event的keyCode属性值是不一样的。

  onkeypress事件中keyCode属性值为触发键字符代码,keyup/keydown事件为键盘代码。

  字符代码和键盘代码区别

  • 字符代码 - 表示 ASCII 字符的数字
  • 键盘代码 - 表示键盘上真实键的数字

  这两种类型的值不是都相等的(主要针对字母),例如小写字符 "w" 和大写字符 "W" 有相同的键盘代码,因为他们他们键盘上 ( "W" 代码为 "87"),但是它们有不同的字符代码,两个字符输出是不一样的( "w" 和 "W" 字符代码为 "119" 和 "87")。

  提示: 如果需要知道用户按下的是数字或者功能键 (如 "F1" 或 "5"),建议使用 onkeypress 事件。如果需要知道用户按下的是功能键(如 "F1", "CAPS LOCK" 或 "Home") 可使用 onkeydown 或 onkeyup 事件。

  注意: 在 Firefox 中, keyCode 属性在 onkeypress 事件中是无效的 (为 0)。要兼容firefox,可以一起使用 which 和 keyCode 属性来做兼容。

var x = event.which || event.keyCode;  // 使用 which 或 keyCode, 这样可支持不同浏览器

The events are for completely different purposes. Use keyup and keydown for identifying physical keys and keypress for identifying typed characters. The two are fundamentally different tasks with different events; don't try to mix the two. In particular, keyCode on keypress events is usually redundant and shouldn't be used (except in older IE, but see the linked document below for more on that); for printable keypresses it's usually the same as which and charCode, although there is some variation between browsers.

javascript keyboard events, already linked to in another answer, is the definitive word on this subject for me and has tables describing what each of the different properties returns for each type of key event and each browser.

来源:http://stackoverflow.com/questions/11030532/keypress-and-keyup-why-is-the-keycode-different

加支付宝好友偷能量挖...


原创文章,转载请注明出处:keypress,keyup中keyCode不一样

评论(0)Web开发网
阅读(192)喜欢(0)JavaScript/Ajax开发技巧