简体   繁体   中英

How to see if a modifier key is being held down without catching the keydown event?

I know how to catch keyup and keydown events.

I want my program to see which modifier keys (eg: meta key, control key, alt key, etc.) are currently being held down even if the program didn't observe the keydown events of those keys.

I know that click events and other events can tell me which modifier keys were pressed down when they were fired off, but my program can't wait around for one to occur.

I need my program to check for the modifier keys regularly (say, every 100ms). How would I go about doing this? My program uses jQuery if that helps.

You can store those values in a variable, and check them whenever you want. An event listener will be necessary of course to update that variable:

 // assume no hot key is pressed var object = { ctrlKey: false, altKey: false, shiftKey: false }; // update whenever a keydown or keyup event is fired document.addEventListener("keydown", function(e) { for(var key in object) { if(object.hasOwnProperty(key)) object[key] = e[key]; // update the object from the event e } }); document.addEventListener("keyup", function(e) { for(var key in object) { if(object.hasOwnProperty(key)) object[key] = e[key]; } }); // testing example: function check() { console.log("Checking:"); console.log("Alt key:", object.altKey); console.log("Ctrl key:", object.ctrlKey); console.log("Shift key:", object.shiftKey); } setInterval(check, 1000); // calling check every second without waiting for an event to occur 

Late to the party, but since this shows up on Google, here's a partial solution that's one step closer. From this SO answer :

document.body.onkeydown = function(e) {
  if (e.which === 18) {
    alt_state.textContent = 'pressed';
  }
};

document.body.onkeyup = function(e) {
  if (e.which === 18) {
    alt_state.textContent = 'released';
  }
};

function detectAlt() {
  if (document.webkitHidden) return;
  window.addEventListener('mousemove', function onMove(e) {
    alt_state.textContent = e.altKey ? 'pressed' : 'released';
    window.removeEventListener('mousemove', onMove, false);
  }, false);
}

document.addEventListener('webkitvisibilitychange', detectAlt, false);
window.addEventListener('load', detectAlt, false);

Essentially, set up a mousemove event listener, which contains the modifier key states when fired, and remove the listener after it's fired the first time. Again, still requires an "event" but depending on your application's expected usage, catching the first mousemove event might be sufficient for detecting modifier keys.

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