onKeyPress Vs. onKeyUp and onKeyDown

2018-12-31 16:25发布

问题:

What is the difference between these three events? Upon googling I found that

The KeyDown event is triggered when the user presses a Key.

The KeyUp event is triggered when the user releases a Key.

The KeyPress event is triggered when the user presses & releases a Key. (onKeyDown followed by onKeyUp)

I understand the first two, but isn\'t KeyPress the same as KeyUp? (or is it possible to release a key(KeyUp) without pressing(KeyDown) it?)

This is a bit confusing, can someone clear this up for me?

回答1:

Check here for the archived link originally used in this answer.

From that link:

In theory, the keydown and keyup events represent keys being pressed or released, while the keypress event represents a character being typed. The implementation of the theory is not same in all browsers.



回答2:

KeyPress, KeyUp and KeyDown are analagous to, respectively: Click, MouseUp, and MouseDown.

  1. Down happens first
  2. Press happens second (when text is entered)
  3. Up happens last (when text input is complete).

The exception is webkit, which has an extra event in there:

keydown
keypress
textInput     
keyup

Edit Vsync added a demo snippet a few months ago, but just now I\'ve removed it because it no longer works, giving the following error: \"Uncaught DOMException: Failed to read the \'localStorage\' property from \'Window\': The document is sandboxed and lacks the \'allow-same-origin\' flag.\" You can try it out in a test page, however:

window.addEventListener(\"keyup\", log);
window.addEventListener(\"keypress\", log);
window.addEventListener(\"keydown\", log);

function log(event){
  console.log( event.type );
}


回答3:

onkeydown is fired when the key is down (like in shortcuts; for example, in Ctrl+A, Ctrl is held \'down\'.

onkeyup is fired when the key is released (including modifier/etc keys)

onkeypress is fired as a combination of onkeydown and onkeyup, or depending on keyboard repeat (when onkeyup isn\'t fired). (this repeat behaviour is something that I haven\'t tested. If you do test, add a comment!)

textInput (webkit only) is fired when some text is entered (for example, Shift+A would enter uppercase \'A\', but Ctrl+A would select text and not enter any text input. In that case, all other events are fired)



回答4:

It seems that onkeypress and onkeydown make the same (whithin the small difference of shortcut keys already mentioned above).

You can try this:

    <textarea type=\"text\" onkeypress=\"this.value=this.value + \'onkeypress \'\"></textarea><br/>
    <textarea type=\"text\" onkeydown=\"this.value=this.value + \'onkeydown \'\" ></textarea><br/>
    <textarea type=\"text\" onkeyup=\"this.value=this.value + \'onkeyup \'\" ></textarea><br/>

And you will see that the events onkeypress and onkeydown are both triggered while the key is pressed and not when the key is pressed.

The difference is that the event is triggered not once but many times (as long as you hold the key pressed).

If you use some of these events be aware and handle how many times your code is run.

And sorry for my English the lessons were poor.



回答5:

Most of the answers here are focused more on theory than practical matters and there\'s some big differences between keyup and keypress as it pertains to input field values, at least in Firefox (tested in 43).

If the user types 1 into an empty input element:

  1. The value of the input element will be an empty string (old value) inside the keypress handler

  2. The value of the input element will be 1 (new value) inside the keyup handler.

This is of critical importance if you are doing something that relies on knowing the new value after the input rather than the current value such as inline validation or auto tabbing.

Scenario:

  1. The user types 12345 into an input element.
  2. The user selects the text 12345.
  3. The user types the letter A.

When the keypress event fires after entering the letter A, the text box now contains only the letter A.

But:

  1. Field.val() is 12345.
  2. $Field.val().length is 5
  3. The user selection is an empty string (preventing you from determining what was deleted by overwriting the selection).

So it seems that the browser (Firefox 43) erases the user\'s selection, then fires the keypress event, then updates the fields contents, then fires keyup.



回答6:

The onkeypress event works for all the keys except ALT, CTRL, SHIFT, ESC in all browsers where as onkeydown event works for all keys. Means onkeydown event captures all the keys.



回答7:

Basically, these events act differently on different browser type and version, I created a little jsBin test and you can check the console for find out how these events behavior for your targeted environment, hope this help. http://jsbin.com/zipivadu/10/edit



回答8:

This article by Jan Wolter is the best piece I have came across, you can find the archived copy here if link is dead.

It explains all browser key events really well,

The keydown event occurs when the key is pressed, followed immediately by the keypress event. Then the keyup event is generated when the key is released.

To understand the difference between keydown and keypress, it is useful to distinguish between characters and keys. A key is a physical button on the computer\'s keyboard. A character is a symbol typed by pressing a button. On a US keyboard, hitting the 4 key while holding down the Shift key typically produces a \"dollar sign\" character. This is not necessarily the case on every keyboard in the world. In theory, the keydown and keyup events represent keys being pressed or released, while the keypress event represents a character being typed. In practice, this is not always the way it is implemented.

For a while, some browers fired an additional event, called textInput, immediately after keypress. Early versions of the DOM 3 standard intended this as a replacement for the keypress event, but the whole notion was later revoked. Webkit supported this between versions 525 and 533, and I\'m told IE supported it, but I never detected that, possibly because Webkit required it to be called textInput while IE called it textinput.

There is also an event called input, supported by all browsers, which is fired just after a change is made to to a textarea or input field. Typically keypress will fire, then the typed character will appear in the text area, then input will fire. The input event doesn\'t actually give any information about what key was typed - you\'d have to inspect the textbox to figure it out what changed - so we don\'t really consider it a key event and don\'t really document it here. Though it was originally defined only for textareas and input boxes, I believe there is some movement toward generalizing it to fire on other types of objects as well.



回答9:

On the one hand, there\'s obvious meaning: KeyDown fires when a key is pushed down, KeyUp fires when a pushed button is released, KeyPress fires when a key is pushed and released.

On the the other hand, some keys fire some of these events and don\'t fire others. For instance, KeyPress ignores delete, arrows, home/end, ctrl, alt, shift etc while KeyDown and KeyUp don\'t.

Finally, there\'s some pragmatics. For handling arrows, you\'ll probably need to use onKeyDown: if a user holds \"down\" KeyDown fires several times (and KeyPress fires only once!). Also, in some cases you can easily prevent propagation of KeyDown but can\'t (or can\'t that easily) prevent propagation of KeyUp (for instance, if you want to submit on enter without adding newline to the text field). If you\'d like to adjust height of a text area to the content, you probably won\'t use onKeyDown but rather onKeyPress. I\'ve used all 3 in my project but unfortunately may have forgotten some of pragmatics.



回答10:

Just wanted to share a curiosity:

when using the onkeydown event to activate a JS method, the charcode for that event is NOT the same as the one you get with onkeypress!

For instance the numpad keys will return the same charcodes as the number keys above the letter keys when using onkeypress, but NOT when using onkeydown !

Took me quite a few seconds to figure out why my script which checked for certain charcodes failed when using onkeydown!

Demo: https://www.w3schools.com/code/tryit.asp?filename=FMMBXKZLP1MK

and yes. I do know the definition of the methods are different.. but the thing that is very confusing is that in both methods the result of the event is retrieved using event.keyCode.. but they do not return the same value.. not a very declarative implementation.



回答11:

KeyDown - when you physically push down key

KeyUp - when you physically release a key

KeyPress - as chars are inputted... KeyPress will fire multiple times if you hold down a key, where as the others will only fire once.