简体   繁体   中英

Detecting Alt key in Chrome

In my app I need to handle Alt key press/release to toggle additional information on tooltips. However, the first time Alt is pressed, document loses keyboard focus, because it goes to Chrome's menu. If I click any part of the document, it works again (once).

I can avoid this by calling preventDefault , but that also disables keyboard shortcuts such as Alt+Left/Right, which is undesirable.

I can also handle mousemove and check altKey flag, but it looks very awkward when things only update when mouse is moved.

Is there any way to reliably detect current Alt key state in my situation? I would really rather not switch to a different key.

Update: I suppose the best solution would be to call preventDefault only when a tooltip is active.

  document.addEventListener("keydown", (e) => {
    if (this.curComponent) e.preventDefault();
    if (e.which === 18) {
      this.outer.classList.add("AltKey");
    }
  });
  document.addEventListener("keyup", (e) => {
    if (this.curComponent) e.preventDefault();
    if (e.which === 18) {
      this.outer.classList.remove("AltKey");
    }
  });

I had the same issue and I solved thanks to this answer :

document.addEventListener("keyup", (e) => {
    if (e.key === "Alt") {
        return true; // Instead of e.preventDefault();
    });

return true restores normal behavior of Alt + Left / Right chrome keyboard shortcuts.

Keyboard value both left/ right side ALT = 18

jQuery:

$(document).keyup(function(e){
    if(e.which == 18){
      alert("Alt key press");
    }
});

JavaScript

document.keyup = function(e){
  if(e.which == 18){
    alert("Alt key press");
  }
}

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