简体   繁体   中英

How can I listen for two key press event at a same time in Javascript?

Below code works perfectly fine but I'm trying to achieve here is that I want to listen for ctrl + b key and Output some value according to it.

  document.addEventListener( 'keydown', (event) => {
    event.preventDefault();
    if (event.code === 'ControlLeft') {
      console.log('CTRL Left Pressed')
    }
});

I've tried && operator in below example but it's not working for me.

  document.addEventListener( 'keydown', (event) => {
    event.preventDefault();
    if (event.code === 'ControlLeft' && event.code === 'KeyB') {
      console.log('CTRL Left and b Pressed')
    }
});

Check out this link;

https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/ctrlKey

The KeyboardEvent comes with a ctrlKey property especially for these kinds of uses.

Your code would then become;

document.addEventListener( 'keydown', (event) => {
    event.preventDefault();
    if ( event.code === 'KeyB' && event.ctrlKey === true ) {
      console.log('CTRL Left and b Pressed')
    }
});

 document.addEventListener( 'keydown', (event) => { event.preventDefault(); if( true === event.ctrlKey && 'b' === event.key ) console.log('CTRL+B Combination true;') });
 Press CTRL+B Combination.

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