What preferred way to reconcile keyCode/charCode across browsers?
Based on the properties of the keydown event I would like to ascertain what the current charCode are?
Example.
For the keydown event when the NumPad0, D0, and Colon key is pressed I would like to know what the associated charcode is. Currently I have a map that contains the charcode associated with that keyCode or use the current if cha开发者_如何学JAVArCode is not specified.
keyCode = {
Colon: 186,
D0: 48,
NumPad0: 96,
};
charCodes = {
186: 59,
96: 48,
};
shiftCharCodes = {
186: 58,
48: 41
};
Also in certain cases the keyCodes are different accross browsers?
Example.
The keydown event has different keyCode values across browsers. Colon Key (:/;) - keyCode is 59 on firefox - keyCode is 186 on IE/safari
For more information
http://www.quirksmode.org/js/keys.html
If you're interested in the character code associated with a keypress, you're going to get nowhere with the keydown
event. The keypress
event is the only place this information is available, and is not too problematic for most printable keys.
document.onkeypress = function(evt) {
evt = evt || window.event;
var charCode = evt.which || evt.keyCode;
alert("Character: " + String.fromCharCode(charCode));
};
There are differences between browser behaviour around "special" non-printable keypresses such as function keys. For more information I consider this article by Jan Wolter to be the definitive reference for JavaScript key handling.
Although I generally loath answers like the one I am about to give, I feel it is appropriate:
This is a perfect use case for a library like jQuery, Prototype, Dojo or MooTools.
You don't want to burden yourself with this work, it has already been done.
精彩评论