Is there a way to detect if a key is currently down in Javascript?
是否有一种方法可以检测一个键是否在Javascript中当前处于关闭状态?
I know about the "keydown" event, but that's not what I need. Some time AFTER the key is pressed, I want to be able to detect if it is still pressed down.
我知道“keydown”事件,但那不是我需要的。在按键被按下一段时间后,我希望能够检测到它是否仍然被按下。
P. S. The biggest issue seems to be that after some period of time the key begins to repeat, firing off keydown and keyup events like a fiend. Hopefully there is just a simple isKeyDown(key) function, but if not then this issue will need to be overcome / worked around.
最大的问题似乎是经过一段时间后,钥匙开始重复,像一个恶魔一样触发按键和按键事件。希望只有一个简单的isKeyDown(key)函数,但是如果没有,那么这个问题就需要解决。
51
Is there a way to detect if a key is currently down in Javascript?
是否有一种方法可以检测一个键是否在Javascript中当前处于关闭状态?
Nope. The only possibility is monitoring each keyup
and keydown
and remembering.
不。唯一的可能就是监控每一个按键和按键并记住。
after some period of time the key begins to repeat, firing off keydown and keyup events like a fiend.
一段时间后,这个键开始重复,像一个恶魔一样触发按键和按键事件。
It shouldn't. You'll definitely get keypress
repeating, and in many browsers you'll also get repeated keydown
, but if keyup
repeats, it's a bug.
这是不应该的。你肯定会得到按键重复,在许多浏览器中你也会得到重复按键,但是如果按键重复,那就是一个错误。
Unfortunately it is not a completely unheard-of bug: on Linux, Chromium, and Firefox (when it is being run under GTK+, which it is in popular distros such as Ubuntu) both generate repeating keyup-keypress-keydown sequences for held keys, which are impossible to distinguish from someone hammering the key really fast.
不幸的是,这并不是一个完全前所未闻的bug:在Linux、Chromium和Firefox(在GTK+下运行时,它在流行的发行版(比如Ubuntu)中运行)都为持有的密钥生成重复的按键按下键序列,这是不可能与某人快速敲击密钥区分的。
99
In addition to using keyup
and keydown
listeners to track when is key goes down and back up, there are actually some properties that tell you if certain keys are down.
除了使用keyup和keydown侦听器来跟踪什么时候键是向下和备份的,实际上还有一些属性告诉您某些键是否已经关闭。
window.Onmousemove= function (e) {
if (!e) e = window.event;
if (e.shiftKey) {/*shift is down*/}
if (e.altKey) {/*alt is down*/}
if (e.ctrlKey) {/*ctrl is down*/}
if (e.metaKey) {/*cmd is down*/}
}
This are available on all browser generated event objects, such as those from keydown
, keyup
, and keypress
, so you don't have to use mousemove.
这在所有浏览器生成的事件对象上都是可用的,比如keydown、keyup和keypress,所以您不必使用mousemove。
I tried generating my own event objects with document.createEvent('KeyboardEvent')
and document.createEvent('KeyboardEvent')
and looking for e.shiftKey
and such, but I had no luck.
我尝试使用document.createEvent('KeyboardEvent')和document.createEvent('KeyboardEvent')生成我自己的事件对象,并查找e。轮班等等,但我没有运气。
I'm using Chrome 17 on Mac
我在Mac电脑上使用Chrome 17
25
My solution:
我的解决方案:
var keys = {};
window.Onkeyup= function(e) { keys[e.keyCode] = false; }
window.Onkeydown= function(e) { keys[e.keyCode] = true; }
I can now check if any key is pressed anywhere else in the script by checking
我现在可以通过检查来检查脚本中的其他地方是否按了键
keys["code of the key"]
If it's true, the key is pressed.
如果是真的,就按下键。
10
I don't believe there is anything like an isKeyDown function, but you could write your own.
我不相信有任何类似于isKeyDown函数的东西,但是您可以自己编写。
Basically, create an array whose length is the number of keys you want to monitor. Then using the documents/pages/controls keyUp and keyDown events, update the array with that key's state.
基本上,创建一个数组,它的长度是要监视的键的数量。然后使用document /pages/controls keyUp和keyDown事件,使用该键的状态更新数组。
Then write a function that checks if a certain key is down and returns a bool.
然后编写一个函数,检查某个键是否为down并返回bool。
var keyEnum = { W_Key:0, A_Key:1, S_Key:2, D_Key:3 };
var keyArray = new Array(4);
function onKeyDown()
{
// Detect which key was pressed
if( key == 'w' )
keyArray[keyEnum.W_Key] = true;
// Repeat for each key you care about...
}
function onKeyUp()
{
// Detect which key was released
if( key == 'w' )
keyArray[keyEnum.W_Key] = false;
// Repeat for each key you care about...
}
function isKeyDown(key)
{
return keyArray[key];
}
That should accomplish what you want.
那应该实现你想要的。
1
Other people have asked this kind of question before (though I don't see any obvious dupes here right now).
其他人以前也问过这样的问题(尽管我现在没有看到任何明显的杜撰)。
I think the answer is that the keydown
event (and its twin keyup
) are all the info you get. Repeating is wired pretty firmly into the operating system, and an application program doesn't get much of an opportunity to query the BIOS for the actual state of the key.
我认为答案是keydown事件(以及它的双关键字)是你得到的所有信息。重复非常牢固地连接到操作系统中,而应用程序没有太多机会查询BIOS中键的实际状态。
What you can do, and perhaps have to if you need to get this working, is to programmatically de-bounce the key. Essentially, you can evaluate keydown
and keyup
yourself but ignore a keyup
event if it takes place too quickly after the last keydown
... or essentially, you should delay your response to keyup
long enough to be sure there's not another keydown
event following with something like 0.25 seconds of the keyup
.
您可以做的,如果您需要让这个工作,那么可能必须做的就是以编程方式反弹键。本质上,您可以自己评估keydown和keyup,但如果keyupevent在最后一个keydown之后发生得太快,您可以忽略它……或者从本质上说,您应该将对keyup的响应延迟足够长的时间,以确保不会有另一个keydown事件以类似于0.25秒的keyup的方式发生。
This would involve using a timer activity, and recording the millisecond times for previous events. I can't say it's a very appealing solution, but...
这将涉及使用一个计时器活动,并为以前的事件记录毫秒数。我不能说这是一个很吸引人的解决方案,但是……
1
/*
Tracks what keys are currently down on the keyboard
*/
function keyboard_module(onUpdate){
var kb = {};
var unicode_mapping = {};
document.Onkeydown= function(e){
var unicode=e.charCode? e.charCode : e.keyCode
var key = getKey(unicode);
kb[key] = true;
if(onUpdate){
onUpdate(kb);
}
}
document.Onkeyup= function(e){
var unicode=e.charCode? e.charCode : e.keyCode
var key = getKey(unicode);
delete kb[key];
if(onUpdate){
onUpdate(kb);
}
}
function getKey(unicode){
if(unicode_mapping[unicode]){
var key = unicode_mapping[unicode];
}else{
var key= unicode_mapping[unicode] = String.fromCharCode(unicode);
}
return key;
}
return kb;
}
function testing(kb){
console.log('These are the down keys', kb);
}
var keyboard = keyboard_module(testing);
....
//somewhere else in the code
if(keyboard['K']){/*do something special */}
1
The following code is what I'm using:
下面的代码是我正在使用的:
var altKeyDownCount = 0;
window.Onkeydown= function (e) {
if (!e) e = window.event;
if (e.altKey) {
altKeyDownCount++;
if (30
When the user keeps holding down the Alt key for some time (about 2 seconds), a group of labels (class='key hidden') appears. When the Alt key is released, the labels disappear. jQuery and Bootstrap are both used.
当用户按住Alt键一段时间(大约2秒)时,会出现一组标签(class='key hidden')。当Alt键被释放时,标签就会消失。jQuery和Bootstrap都使用过。
0
Look at this answer, and use onkeyup
and onkeydown
. Here is more specific info about those events.
看看这个答案,使用onkeyup和onkeydown。这里有关于这些事件的更具体的信息。
0
I know this is very old question, however there is a very lightweight (~.5Kb) Javascript library that effectively "patches" the inconsistent firing of keyboard event handlers when using the DOM API.
我知道这是一个非常古老的问题,但是有一个非常轻量级(~. 5kb)的Javascript库,它在使用DOM API时有效地“修补”了键盘事件处理程序不一致的触发。
The library is Keydrown.
图书馆是Keydrown。
Here's the operative code sample that has worked well for my purposes by just changing the key on which to set the listener:
这里有一个运行良好的代码示例,它通过改变设置监听器的键来达到我的目的:
kd.P.down(function () {
console.log('The "P" key is being held down!');
});
kd.P.up(function () {
console.clear();
});
// This update loop is the heartbeat of Keydrown
kd.run(function () {
kd.tick();
});
I've incorporated Keydrown into my client-side Javascript for a proper pause animation in a Red Light Green Light game I'm writing. You can view the entire game here. (Note: If you're reading this in the future, the game should be code complete and playable :-D!)
在我正在编写的一个红绿灯游戏中,我将key溺死在我的客户端Javascript中,以获得一个适当的暂停动画。你可以在这里看到整个游戏。(注意:如果你将来要读这篇文章,游戏应该是完整的代码并且可以玩:-D!)
I hope this helps.
我希望这可以帮助。
0
Ended up here to check if there was something builtin to the browser already, but it seems there isn't. This is my solution (very similar to Robert's answer):
最后在这里检查浏览器是否已经内置了一些东西,但似乎没有。这是我的解决方案(非常类似于罗伯特的答案):
"use strict";
let is_key_down = (() => {
let state = {};
window.addEventListener('keyup', (e) => state[e.key] = false);
window.addEventListener('keydown', (e) => state[e.key] = true);
return (key) => state.hasOwnProperty(key) && state[key] || false;
})();
You can then check if a key is pressed with is_key_down('ArrowLeft')
.
然后,您可以使用is_key_down(“ArrowLeft”)检查是否按了键。
-2
$('#mytextbox').keydown(function (e) {
if (e.keyCode == 13) {
if (e.altKey) {
alert("alt is pressed");
}
}
});
if you press alt + enter, you will see the alert.
如果你按alt + enter,你会看到警报。