keypress and keyup - why is the keyCode different?

后端 未结 3 1986
闹比i
闹比i 2020-11-28 07:00

Related: JavaScript KeyCode vs CharCode

Here is some code you can try at home or in a jsfiddle:

el.addEventListener( \'keyup\', function( e ) { 
             


        
相关标签:
3条回答
  • 2020-11-28 07:23

    Well, I stumbled upon one difference when i was trying to copy user's entry from one input of the form to some other part of the form , which I had locked for my for users to edit. What i found was, that whenever a user moved to the next label using key upon completing the input, one last keyboard entry was missed in the copied entry when I used eventListener to keypress and this got resolved on using keyup.

    So, in conclusion Keypress listens to the state at the instant when the key was pressed, leaving aside the result of keypress, whereas keyup listens to the system status after the key has been pressed and includes the result of the keypress.

    0 讨论(0)
  • 2020-11-28 07:31

    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.

    Jan Wolter's article on key 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.

    0 讨论(0)
  • 2020-11-28 07:40

    There is a good article on quirksmode.org answering exactly that question. You might also want to look at Unixpapa's results.

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