jQuery Event Keypress: Which key was pressed? A-Z, & @

后端 未结 3 806
小蘑菇
小蘑菇 2021-01-06 00:41

on a keydown I get the following from jQuery:

jQuery.Event
altKey: false
attrChange: undefined
attrName: undefined
bubbles: true
button: undefined
cancelable         


        
相关标签:
3条回答
  • 2021-01-06 01:08

    Here is the fiddle that matches your exact requirement
    http://jsfiddle.net/cSc7r/

    You may have to use

      String.fromCharCode(key_event.which);
    

    or

      String.fromCharCode(event.keyCode); // For IE
    

    However if you want to run any event on key press here is a nice plugin to make it very easily. Please check this fiddle http://jsfiddle.net/zUc4Z/.

    0 讨论(0)
  • 2021-01-06 01:08

    Not sure if you want to run events when the keys are pressed but you can try https://github.com/jeresig/jquery.hotkeys

    Otherwise you can check if the shift key was pressed in the event from your code. Havent seen a library that handles this for you

    0 讨论(0)
  • 2021-01-06 01:15

    There are three keyboard events you can trap: keyup, keydown, and keypress. The first two behave the way you've observed, and the latter behaves the way you seem to want.

    You need to understand the difference between a key and the character(s) associated with that key.

    As explained in the jQuery doco (admittedly it is kind of buried), the keyup and keydown events give a keyCode that corresponds to the actual physical key on the keyboard, so uppercase "A" and lowercase "a" will have the same code, as will "2" and "@" - but note that the "2" key above the "W" has a different code to the "2" key on the numeric keypad. The event.shiftKey property will tell you whether shift was down at the time the key was pressed. Those two events can also check for non-text type keys like the arrow keys, Ctrl, Home, etc.

    On the other hand, the keypress event gives a keyCode corresponding to the character, so "A" and "a" will give different keyCodes, as will "2" and "@". So keypress may be better suited to your needs.

    (By the way, this isn't a jQuery thing as such, this is normal behaviour even with "plain" JavaScript, though jQuery attempts to normalise behaviour across different browsers. One such normalisation is that jQuery makes sure that event.which will work consistently, so you should use event.which to get the code rather than event.keyCode.)

    0 讨论(0)
提交回复
热议问题