Why can I preventDefault event on keydown but not on keyup with Javascript?

后端 未结 2 1188
独厮守ぢ
独厮守ぢ 2021-01-03 02:29

When using .keydown I can capture keydown event, then check and prevent default action (display the character).

When using .keyup I cannot?

2条回答
  •  一向
    一向 (楼主)
    2021-01-03 02:49

    the keydown() event is fired when the key is hit, meaning that code can be executed before the key is released.

    When the key is pressed code can prevent an action, because it simply hasn't happened yet, whereas on the keyup() event, it already has.

    e.g. a character has already been inserted into an input field when triggering keyup()

    in general, keydown and keyup produce the same keycodes (when used with a given event) however keypress gives you the physical key pressed (ASCII code returned rather than keyCode)

提交回复
热议问题