Use keyCode to determine which key the user pressed

Before judging which key is pressed, we first need to understand the keyboard events:

There are three keyboard events (addEventListener listeners do not need to add on to register events):

  • Triggered when the onkeyup   button is released
  • Triggered when the onkeydown  button is pressed
  • onkeypress   fires when a key is pressed (case-sensitive, invalid for function keys such as ctrl, arrow, shift)


onkeyup

Trigger an event when the mouse is released

<script>
     document.addEventListener('keyup',function(){
         alert('我被松开了')
     })
</script>

onkeydown:

<script>
     document.addEventListener('keydown',function(){
         alert('我被按下了')
     })
</script>

Note : most of the effects of onkeydown and onkeypress are the same, but onkeypress cannot be triggered by function keys, onkeydown can, and onkeypress can be case-sensitive


e.keyCode: Get the ASCII code of the pressed key

This method of the keyboard object can return the ASCII code of the pressed key. Because keyup and keydown are not case-sensitive, the ASCII code of the output key is always the lowercase value. For example, when a and A are pressed, the output value is 65. keypress is case sensitive, so the output of a and A are different

keyup and keydown keyboard events : the output value of a and A are both 65

<script>
     document.addEventListener('keydown',function(e){
       alert(e.keyCode)  // a 和 A 的输出结果为65
     })
</script>

keypress keyboard event : the output value of a is 97, the output value of A is 65

<script>
     document.addEventListener('keypress',function(e){
       alert(e.keyCode)
     })
</script>

Guess you like

Origin blog.csdn.net/weixin_52212950/article/details/123261126