问题描述
当有人按住修饰键(Shift,Alt,Ctrl)时,我的应用程序会更改其状态.我使用keydown/keyup事件跟踪修饰键:
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:
- 按住Shift键
- 单击指向我的应用程序的链接,它将在新窗口中打开
- 释放Shift键
keyup
事件在未聚焦时不会在我的页面上触发,因此当我再次聚焦在应用程序的选项卡上时,我的应用程序将显示,它将显示仍在按下Shift键.
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.
如果页面可见性事件具有修饰键属性,那就很好了. las,他们没有.
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);
推荐答案
我到目前为止取得的最好成绩:
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);
按alt键,然后单击链接: jsbin .
Press alt key and click on the link: jsbin.
它依赖于mousemove事件,与load
和visibilitychange
事件不同,该事件具有altKey
属性.不利的一面是,直到有人移动鼠标时,它才会检测到altKey.
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.
这篇关于检测按下的修饰键而不触发键盘或鼠标事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!