简体   繁体   中英

Listening for keydown / keypress events and differentiate between one and two digit numbers

I'm using an eventListener to detect numeric options in my vue app:

window.addEventListener("keydown", function (e) {
      switch (e.key) {
        case 1:
          // do stuff
          break;
        case 2:
          // do other stuff
      }
}

Since I have more than 9 options, I was wondering what the most sensible way would be to differentiate if the user is entering a one or two digit numer (eg, 1 vs 11 )?

Ended up adapting the solution described in this blog post , by pushing all keystrokes into an array, which is cleared if there is no input after 1 sec.

    let keys = [];
    let timeout = null;

    window.addEventListener("keydown", function (e) {
      
      keys.push(e.key);
      clearTimeout(timeout);
      timeout = setTimeout(function () {
          let input = parseInt(keys.join(""));
 
            switch (input) {
              case 1:
                // do stuff
                break;
              case 11:
                // do other stuff

          }          
          keys = [];  
      }, 1000);
    });

The switch statement is doing an implicit type conversion since e.key is a string, and the switch case specifiers are numbers. If you don't have more than 35 options, using base 36 digits ('1'-'9' and 'a'-'z') could be the easiest solution, in conjunction with constructing the switch statement along the lines of

  switch( e.key.toLowerCase() {
  case '1':  ... break;
  .
  .
  .
  case 'z':  ... break;
  }

I would hesitate before telling users they must hit a second digit within 500ms and wait that long before the first key they hit is recognized. :-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM