JavaScript跟踪准确按下了哪些键 [英] JavaScript keep track of which keys are down accurately

查看:82
本文介绍了JavaScript跟踪准确按下了哪些键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个永远运行60FPS循环的Web应用程序,有时我想检查一下钥匙是否按下.所以我做了

I have a web app that's running a 60FPS loop forever and I sometimes want to check whether a key is down now. So I made

var keydown = []
window.addEventListener("keydown", function(e){keydown[e.keyCode]=true})
window.addEventListener("keyup", function(e){keydown[e.keyCode]=false})
function loop() {
    if(keydown[17]) console.log("Control is down.")
    if(keydown[71]) console.log("F is down.")
}
setInterval(loop, 16)

问题在于,如果用户按下Ctrl + F来搜索页面,那么当他们放开时,查找窗口将具有焦点,因此不会触发键控.因此我的应用程序认为控制和F永远消失了.因此,我为控制键添加了此技巧:

The problem is that if the user presses control+F to search the page, then when they let go, the find window has focus and thus keyup does not fire. So my app thinks control and F are down forever. So I added this hack for the control key:

// Hack to fix control key being down forever.
window.addEventListener("mousemove", function(e){
    if(keydown[17] && !e.ctrlKey) {
        keydown[17] = false
    }
})

如果F键永远按下,我该怎么办?我已经尝试过重新设置能见度更改上的所有键,但是在用户搜索时不会触发.

What do I do about it thinking the F key is down forever? I have tried resetting all keys on visibilitychange but it doesn't fire when the user searches.

这里是演示和来源: http://touchbasicapp.com/testkeyup.html

此错误位于Windows和Mac,Chrome和Safari上.

This bug is on windows and mac, Chrome and Safari.

推荐答案

当窗口失去焦点(模糊事件)时清除数组可能是您的最佳选择.

Clearing the array when the window loses focus (blur event) is probably your best option.

window.addEventListener("blur", function(e) {
    keydown = [];
});

不幸的是,我认为无法保证在打开搜索界面时浏览器必然会触发模糊事件,但他们可能应该这样做.

Unfortunately, I don't think there's any guarantee the browser will necessarily fire a blur event in the case of the search interface opening, but they probably should.

这篇关于JavaScript跟踪准确按下了哪些键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆