问题
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:
- Hold Shift key
- Click on a link to my app, it will open in a new window
- 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:
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); } };
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