简体   繁体   中英

Alt keyup lost when doing alt-tab

I'm detecting alt with the following code. It works, but when I do alt - tab to switch to another program, I get a keydown of 18 (alt) and no keyup, and alt remains pressed. How can I solve this?

var altPressed = false;

$(document).keydown(function(evt) {
    console.log("keydown", evt.which);
    switch (evt.which) {
    case 18: 
        altPressed = true;
    break;
    }
}).keyup(function(evt) {
    console.log("keyup", evt.which);
    switch (evt.which) {
    case 18: 
        altPressed = false;
    break;
}

Alt + Tab removes the focus on your main window, thus the keyup event will not fire.

Here's a probable solution you could use. I'm not sure if escape is being registered from which though, might have to use keyCode instead.

Example:

var altPressed = false;

$(document).keydown(function(evt) {
    console.log("keydown", evt.which);
    switch (evt.which) {
    case 18:
        altPressed = true;
        break;
    case 9: //tab key
    case 27: //escape key
        if(altPressed) {
             altPressed = false;
        }
    break;
    }
}).keyup(function(evt) {
    console.log("keyup", evt.which);
    switch (evt.which) {
    case 18: 
        altPressed = false;
    break;
});

As @Nathan points out correctly: Alt + Tab removes the focus on the main window, thus the keyup event will not fire.

Here is a solution that does not require jQuery and works for every focus loss:

Using the Blur event

Here is a VanillaJS example using your code, read more about the blur event in MDN docs

let altPressed = false;

function keyDownHandler(evt) {
  if(evt.key === "Alt")
    altPressed = true
}

function keyUpHandler(evt) {
  if(evt.key === "Alt")
    altPressed = false
}

document.addEventListener('keydown', keyDownHandler)
document.addEventListener('keyup', keyUpHandler)
window.addEventListener('blur', keyUpHandler)

Note: same as with @Nathans answer, this will not know whether the key is still down when moving back to the page (but with alt+tab it would not anyways).

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