Detect pressed modifier keys without triggering keyboard or mouse events

大兔子大兔子 提交于 2019-12-22 03:48:13

问题


My app changes its state when a person holds modifier keys (Shift, Alt, Ctrl). I track modifier keys using keydown/keyup events:

var altPressed;
window.onkeydown = window.onkeyup = function(e) {
    altPressed = e.altKey;
}

Keyboard events don’t trigger outside of the browser tab. Now, imagine the following scenario:

  1. Hold Shift key
  2. Click on a link to my app, it will open in a new window
  3. Release Shift key

keyup event won’t fire on my page when it isn’t focused so my app will show when I focus on my app’s tab again it will show the Shift key still being pressed.

Would be nice if page visibility events had modifier key properties. Alas, they don’t.

document.addEventListener('webkitvisibilitychange', function(e) {
    if (document.webkitHidden) return;

    e.altKey // undefined :(

}, false);

回答1:


The best I came up so far:

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);

Press alt key and click on the link: jsbin.

It relies on mousemove event which, unlike load and visibilitychange events, has altKey property. As a downside, it won’t detect altKey until a person moves the mouse.




回答2:


I could think of 2 options:

  1. Use a timed "alt status" --> after 2 seconds declare alt unpressed.

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

  2. When visibility is lost simply reset all alt flags.

    document.addEventListener('webkitvisibilitychange', function(e) {
        if (document.webkitHidden){
            altPressed = "";
            return;
        }
    }, false);
    

try this: http://jsbin.com/jihuyibu/1/edit It's my best guess, even so it never comes out perfectly.



来源:https://stackoverflow.com/questions/22086059/detect-pressed-modifier-keys-without-triggering-keyboard-or-mouse-events

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!