onKeyPress Vs. onKeyUp and onKeyDown

前端 未结 12 783
醉酒成梦
醉酒成梦 2020-11-22 07:44

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

  • The onKeyDown event is triggered when the user pre
12条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-22 07:56

    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.

提交回复
热议问题