The cause of

Today I saw A requirement that if you use the Alt+A shortcut to do something.

Can listen for keyboard events

Keydown keyUp KeyPress can listen for keyboard events. The difference between them is:

  • Keypress can only capture a single character
  • Keypress can capture the case of individual characters
  • Keypress does not distinguish between numeric characters on the keypad and the main keyboard
  • Keypress does not listen for Alt, CTRL, Enter, or Shift
  • Keydown Keyup captures key combinations
  • Keydown KeyUp is not case-sensitive
  • Keydown Keyup distinguishes numeric characters on the keypad and the main keyboard

Listen for a single keyboard key

    // document.addEventListener('keydown',(e)=>{
    // console.log(e);
    // })
    // document.addEventListener('keypress',(e)=>{
    // console.log(e);
    // })
    document.addEventListener('keyup'.(e) = >{
      console.log(e);
    })
Copy the code

Listen for two-key combination events

Ctrl + C, for example

 document.addEventListener('keydown'.(e) = >{
      if(e.ctrlKey&&e.keyCode===67) {console.log('Ctrl+c'); }})Copy the code

CtrlKey, altKey, shiftKey corresponding to E are true when CTRL, Alt, Shift are pressed. On the Mac, the Command key is metaKey. Note: This can only be CTRL, Alt, Shift and a normal key.

How to judge normal two-key or three-key change

My idea is: within a specified period of time (say 300ms), if a key is pressed, the changed key is saved to the specified object. If it times out or has been triggered, the saved object is restored. Then determine whether the object also has the key we want to listen for.

    // A common two-key example
    let firstTime = 0
    let doubleEvent = {}
    document.addEventListener('keyup'.(e) = >{
      let currentTime = Date.now()
      if(firstTime===0){
        firstTime =  currentTime
        doubleEvent[e.key] = true
      }else if(currentTime-firstTime>300) {/ / more than 300 ms
        firstTime = 0
        doubleEvent = {}
      }else{
        doubleEvent[e.key] = true
      }
      if(doubleEvent.b&&doubleEvent.c){
        console.log('b+c');
        doubleEvent = {}
        firstTime = 0}})Copy the code

PS: If you have other ideas, please advise. thank you