10

I'm working on key handling in Javascript. I have done some research and I'd like to know whether I have a correct understanding of key handling.

KeyDown/KeyUp Event The key down and key up events are supported by IE7+ and Firefox 3.5+ I didn't check the earlier versions of the browsers, but I guess that they also support these events.

Is it correct to say that each key on the keyboard will always have a keycode.

CharCode

CharCode value is available on the keypress.Majority of the keys will have the charcodes that represent the actual value. Some keys won't have a charcode associated with them. E.g. backspace, delete, arrow keys.

Am I correct to say that on the keypress the charcode will be the same as the keycode?

Order of the events

  • KeyDown
  • KeyPress
  • KeyUp

Does this order differ from browser to browser? For example I have two functions. First is bound to KeyDown event, second is bound to the KeyPress event. Calling a KeyPress event means that the KeyDown event will also be called, when I want only one of these events to work.

Finally I have been considering on using different key handling routines depending on the version browser. For example:

  • Check browser version
  • Get key handling routine depending on the browser version

This will introduce additional code, but should simplify the maintenance. Also, in the future, when I want to provide a support for a different browser, I can simply add another routine and it won't affect existing character handling routine.

So far I have been reading http://www.quirksmode.org

4

3 回答 3

7

请参阅以下页面,他们将回答您的问题:

onkeydown 事件onkeypress 事件keyCode 属性charCode 属性哪个属性

于 2010-08-13T10:46:52.227 回答
6

Jan Wolter 的以下文章从未让我失望,并且绝对是我所见过的关于浏览器关键事件的最佳资源:http: //unixpapa.com/js/key.html。它回答了你提出的所有问题。

需要强调的一点是,通过谨慎使用您可以随意使用的关键事件属性,您几乎可以肯定永远不需要在您的密钥处理代码中嗅探特定浏览器。

于 2010-08-13T19:32:33.417 回答
0

2015 年更新:

根据 MDN event.charCodeevent.keyCode并且event.which都已被弃用。event.key是检查哪个键被按下的最新和最热门的方法。

它看起来很容易使用,但浏览器支持并不完美。我们现在所拥有的只是 Chrome 45+(AFAIK 尚未推出)、Firefox 23+ 和 IE 9+ 的部分支持。

于 2015-05-21T10:23:47.580 回答