-->

JavaScript key handling and browser compatibility

2019-03-26 13:07发布

问题:

I'm working on key handling in java script. 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

回答1:

See the following pages, they will answer your quetions:

onkeydown event, onkeypress event, keyCode property, charCode property, which property



回答2:

The following article by Jan Wolter has never failed me and is far and away the best resource on browser key events I've seen: http://unixpapa.com/js/key.html. It answers all the questions you posed.

One thing to emphasize is that with careful use of the key event properties at your disposal you will almost certainly never need to sniff for a particular browser in your key handling code.



回答3:

2015 update:

According to MDN event.charCode, event.keyCode and event.which have all been deprecated. event.key is the newest and hottest way to check which key has been pressed.

It looks easy to use, but browser support isn’t perfect. All we have now is partial support in Chrome 45+ (not out yet AFAIK), Firefox 23+ and IE 9+.