onKeyPress Vs. onKeyUp and onKeyDown

前端 未结 12 867
醉酒成梦
醉酒成梦 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 08:06

    A few practical facts that might be useful to decide which event to handle (run the script below and focus on the input box):

    $('input').on('keyup keydown keypress',e=>console.log(e.type, e.keyCode, e.which, e.key))
    
    

    Pressing:

    • non inserting/typing keys (e.g. Shift, Ctrl) will not trigger a keypress. Press Ctrl and release it:

      keydown 17 17 Control

      keyup 17 17 Control

    • keys from keyboards that apply characters transformations to other characters may lead to Dead and duplicate "keys" (e.g. ~, ´) on keydown. Press ´ and release it in order to display a double ´´:

      keydown 192 192 Dead

      keydown 192 192 ´´

      keypress 180 180 ´

      keypress 180 180 ´

      keyup 192 192 Dead

    Additionally, non typing inputs (e.g. ranged ) will still trigger all keyup, keydown and keypress events according to the pressed keys.

提交回复
热议问题