[英]Can I detect if key is being held down when window gains focus?
I am tracking keyDown and keyUp to show whether or not the shift key is being pressed in JavaScript: 我正在跟踪keyDown和keyUp以显示是否在JavaScript中按下了shift键:
window.addEventListener("keydown",doKeyDown,false);
window.addEventListener("keyup",doKeyUp,false);
var shiftKeyDown = false;
function doKeyDown(e) {
if (e.keyCode==16) { shiftKeyDown = true; }
}
function doKeyUp(e) {
if (e.keyCode==16) { shiftKeyDown = false; }
}
However, the user might hold the shift key down while giving focus to another window, so my window never hears the keyup
event. 但是,用户在将焦点移到另一个窗口时可能会按住Shift键,因此我的窗口从没有听到
keyup
事件。 Am I right in thinking that there is no way to detect the state of the shift key when the window gains focus again, so I can correctly update shiftKeyDown
? 我是否认为在窗口再次获得焦点时无法检测Shift键的状态是正确的,所以我可以正确地更新
shiftKeyDown
?
You can add a window.onBlur
eventlistener and set shiftKeyDown
to false, when the windows loses focus. 当窗口失去焦点时,您可以添加
window.onBlur
侦听器,并将shiftKeyDown
设置为false。
window.addEventListener("blur",onBlur,false);
function onBlur(e){
shiftKeyDown = false
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.