简体   繁体   中英

How to capture keyboard inputs like Windows explorer

I have custom dropdown select and capturing keydown event which triggers an event for each input pressed on keyboard.

document.addEventListener('keydown', (event) => {
  const keyName = event.key;
  console.log('keydown event\n\n' + 'key: ' + keyName);
}); 

在此处输入图片说明

Pressing "t" and "w" triggers event two successive events. But I need to capture "tw" as my search term then highlight it in dropdown. (Or) Just I need to capture all keys pressed continuously.

I am looking for something in Windows explorer where quickly pressing "d" & "e" highlights "Dev Tools".

在此处输入图片说明

How to capture these in JavaScript with proper timeout or something?

Maybe like this:

let pressed = [];
let timeoutId;

document.addEventListener('keypress', e => {
  pressed.push(e.key);

  if (timeoutId) {
    clearTimeout(timeoutId);
  }

  timeoutId = setTimeout(() => {
    console.log(pressed.join(''));
    pressed = [];
  }, 400); //300-400ms timeout is optimal
});

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