如何使用 JavaScript 检测是否同时按下多个键?
我正在尝试开发一个 JavaScript 游戏引擎,并且遇到了这个问题:
- 当我按 SPACE 时,角色会跳跃。
- 当我按 → 时,角色向右移动。
问题是,当我按向右然后按空格时,角色会跳跃然后停止移动。
我使用 keydown
函数来按下按键。如何检查是否同时按下了多个键?
I'm trying to develop a JavaScript game engine and I've came across this problem:
- When I press SPACE the character jumps.
- When I press → the character moves right.
The problem is that when I'm pressing right and then press space, the character jumps and then stops moving.
I use the keydown
function to get the key pressed. How can I check if there are multiple keys pressed at once?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(20)
注意:keyCode 现已弃用。< /strong>
如果您理解这个概念,多次击键检测很容易
。我的做法是这样的:
这段代码非常简单:由于计算机一次只传递一次击键,因此创建一个数组来跟踪多个键。然后可以使用该数组一次检查一个或多个键。
只是为了解释一下,假设您按 A 和 B,每个都会触发一个
keydown
事件来设置map[e.keyCode]< /code> 为
e.type == keydown
的值,其计算结果为 true 或 false。现在,map[65]
和map[66]
均设置为true
。当您松开A
时,会触发keyup
事件,导致相同的逻辑为map[65]
确定相反的结果 (A) ,现在为 false,但由于map[66]
(B) 仍处于“按下”状态(它尚未触发 keyup 事件),因此它仍然是正确。。通过这两个事件,
map
数组如下所示:您现在可以执行两件事:
A) 按键记录器 (example) 可以创建作为参考,供以后需要快速找出一个或多个关键代码时参考。假设您已经定义了一个 html 元素并使用变量
element
指向它。注意:您可以通过元素的
id
属性轻松获取元素。这将创建一个 html 元素,可以使用
element
在 javascript 中轻松引用该元素,您甚至不必使用
document.getElementById()
或$() 来抓取它。但出于兼容性考虑,更广泛推荐使用 jQuery 的
$()
。只需确保 script 标记位于 HTML 正文之后。 优化提示:大多数大牌网站都会将script标签放在body标签之后进行优化。这是因为脚本标签会阻止进一步的元素加载,直到其脚本下载完成。将其放在内容之前可以让内容提前加载。
B(这是您感兴趣的地方) 您可以在
/*insertconditionalhere*/
所在的位置一次检查一个或多个键,例如:>编辑:这不是最易读的片段。可读性很重要,所以你可以尝试这样的方法,让眼睛更舒服:
用法:
这样更好吗?
(编辑结束)
此示例检查 CtrlShiftA、CtrlShift B 和 CtrlShiftC
这么
简单
:)
就 根据规则,记录代码是一种很好的做法,尤其是像关键代码(例如
// CTRL+ENTER
)这样的内容,这样您就可以记住它们是什么。您还应该按照与文档相同的顺序放置关键代码(
CTRL+ENTER => map[17] && map[13]
,而不是map[13] & ;&地图[17]
)。这样,当您需要返回并编辑代码时,您就不会感到困惑。if-else 链的陷阱
如果检查不同数量的组合(例如 CtrlShiftAltEnter 和 < kbd>CtrlEnter),将较小的组合放在较大的组合之后,否则较小的组合将覆盖较大的组合(如果它们足够相似)。示例:
问题:“即使我没有按下按键,此组合键也会持续激活”
在处理警报或任何从主窗口获取焦点的内容时,您可能需要包含
map = []
条件完成后重置数组。这是因为有些东西(例如alert()
)会将焦点从主窗口移开,并导致“keyup”事件无法触发。例如:问题:浏览器默认值
这是我发现的一件烦人的事情,其中包含解决方案:
问题:由于浏览器通常对组合键有默认操作(例如 CtrlD 激活)书签窗口,或 CtrlShiftC 在 maxthon 上激活 skynote),您可能还需要添加
return false
在map = []
之后,这样当“复制文件”功能被置于 CtrlD 上时,您网站的用户就不会感到沮丧,改为为页面添加书签。如果不
返回 false
,书签窗口就会弹出,这会让用户感到沮丧。return 语句(新)
好的,所以您并不总是想在此时退出该函数。这就是
event.preventDefault()
函数存在的原因。它的作用是设置一个内部标志,告诉解释器不允许允许浏览器运行其默认操作。之后,函数继续执行(而return
将立即退出函数)。在决定是使用
return false
还是e.preventDefault()
之前,请先了解这种区别event.keyCode
已弃用用户 SeanVieira 在评论中指出
event.keyCode
已被弃用。在那里,他给出了一个很好的替代方案:
event.key
,它返回被按下的键的字符串表示形式,例如"a"
代表 A ,或"Shift"
表示 Shift。我继续编写了一个工具来检查所述字符串。
element.onevent
与element.addEventListener
使用
addEventListener
注册的处理程序可以堆叠,并按照注册的顺序调用,同时设置.onevent
直接相当激进,会覆盖您以前拥有的任何内容。.onevent
属性似乎会覆盖所有内容,并且ev.preventDefault()
和return false;
的行为可能相当不可预测。无论哪种情况,通过 addEventlistener 注册的处理程序似乎都更容易编写和推理。
Internet Explorer 的非标准实现中还有
attachEvent("oneevent",callback)
,但这已超出弃用范围,甚至不属于 JavaScript(它属于一种名为 的深奥语言) JScript)。尽可能避免使用多语言代码将符合您的最佳利益。辅助类
为了解决混淆/投诉,我编写了一个执行此抽象的“类”(pastebin 链接) :
这个类并不能完成所有事情,也不能处理所有可以想象的用例。我不是图书馆人。但对于一般的交互使用来说应该没问题。
要使用此类,请创建一个实例并将其指向要与键盘输入关联的元素:
这将执行的操作是将新的输入侦听器附加到带有
#txt
的元素(假设它是一个textarea),并为组合键Ctrl+5
设置观察点。当Ctrl
和5
都按下时,您传入的回调函数(在本例中,是一个将"FIVE "
添加到文本区域的函数) )将被调用。该回调与名称print_5
关联,因此要删除它,您只需使用:将
input_txt
与txt
元素分离:这样,如果该对象 (
input_txt
) 被丢弃,垃圾回收可以拾取该对象,并且不会留下旧的僵尸事件侦听器。为了完整起见,这里是该类 API 的快速参考,以 C/Java 风格呈现,以便您知道它们返回什么以及它们期望什么参数。
< strong>更新 2017-12-02 为了响应将其发布到 github 的请求,我创建了一个
更新 2018-07-21 我已经使用声明式编程有一段时间了,现在这种方式是我个人最喜欢的:小提琴,pastebin
一般来说,它适用于您实际想要的情况(ctrl、alt、shift),但如果您需要同时按下
a+w
,则它不会将这些方法“组合”成多键查找太困难了。我希望这篇
详尽解释的答案迷你博客对您有所帮助:)Note: keyCode is now deprecated.
Multiple keystroke detection is easy if you understand the concept
The way I do it is like this:
This code is very simple: Since the computer only passes one keystroke at a time, an array is created to keep track of multiple keys. The array can then be used to check for one or more keys at once.
Just to explain, let's say you press A and B, each fires a
keydown
event that setsmap[e.keyCode]
to the value ofe.type == keydown
, which evaluates to either true or false. Now bothmap[65]
andmap[66]
are set totrue
. When you let go ofA
, thekeyup
event fires, causing the same logic to determine the opposite result formap[65]
(A), which is now false, but sincemap[66]
(B) is still "down" (it hasn't triggered a keyup event), it remains true.The
map
array, through both events, looks like this:There are two things you can do now:
A) A Key logger (example) can be created as a reference for later when you want to quickly figure out one or more key codes. Assuming you have defined an html element and pointed to it with the variable
element
.Note: You can easily grab an element by its
id
attribute.This creates an html element that can be easily referenced in javascript with
element
You don't even have to use
document.getElementById()
or$()
to grab it. But for the sake of compatibility, use of jQuery's$()
is more widely recommended.Just make sure the script tag comes after the body of the HTML. Optimization tip: Most big-name websites put the script tag after the body tag for optimization. This is because the script tag blocks further elements from loading until its script is finished downloading. Putting it ahead of the content allows the content to load beforehand.
B (which is where your interest lies) You can check for one or more keys at a time where
/*insert conditional here*/
was, take this example:Edit: That isn't the most readable snippet. Readability's important, so you could try something like this to make it easier on the eyes:
Usage:
Is this better?
(end of edit)
This example checks for CtrlShiftA, CtrlShiftB, and CtrlShiftC
It's just as simple as that :)
Notes
Keeping Track of KeyCodes
As a general rule, it is good practice to document code, especially things like Key codes (like
// CTRL+ENTER
) so you can remember what they were.You should also put the key codes in the same order as the documentation (
CTRL+ENTER => map[17] && map[13]
, NOTmap[13] && map[17]
). This way you won't ever get confused when you need to go back and edit the code.A gotcha with if-else chains
If checking for combos of differing amounts (like CtrlShiftAltEnter and CtrlEnter), put smaller combos after larger combos, or else the smaller combos will override the larger combos if they are similar enough. Example:
Gotcha: "This key combo keeps activating even though I'm not pressing the keys"
When dealing with alerts or anything that takes focus from the main window, you might want to include
map = []
to reset the array after the condition is done. This is because some things, likealert()
, take the focus away from the main window and cause the 'keyup' event to not trigger. For example:Gotcha: Browser Defaults
Here's an annoying thing I found, with the solution included:
Problem: Since the browser usually has default actions on key combos (like CtrlD activates the bookmark window, or CtrlShiftC activates skynote on maxthon), you might also want to add
return false
aftermap = []
, so users of your site won't get frustrated when the "Duplicate File" function, being put on CtrlD, bookmarks the page instead.Without
return false
, the Bookmark window would pop up, to the dismay of the user.The return statement (new)
Okay, so you don't always want to exit the function at that point. That's why the
event.preventDefault()
function is there. What it does is set an internal flag that tells the interpreter to not allow the browser to run its default action. After that, execution of the function continues (whereasreturn
will immediately exit the function).Understand this distinction before you decide whether to use
return false
ore.preventDefault()
event.keyCode
is deprecatedUser SeanVieira pointed out in the comments that
event.keyCode
is deprecated.There, he gave an excellent alternative:
event.key
, which returns a string representation of the key being pressed, like"a"
for A, or"Shift"
for Shift.I went ahead and cooked up a tool for examining said strings.
element.onevent
vselement.addEventListener
Handlers registered with
addEventListener
can be stacked, and are called in the order of registration, while setting.onevent
directly is rather aggressive and overrides anything you previously had.The
.onevent
property seems to override everything and the behavior ofev.preventDefault()
andreturn false;
can be rather unpredictable.In either case, handlers registered via
addEventlistener
seem to be easier to write and reason about.There is also
attachEvent("onevent", callback)
from Internet Explorer's non-standard implementation, but this is beyond deprecated and doesn't even pertain to JavaScript (it pertains to an esoteric language called JScript). It would be in your best interest to avoid polyglot code as much as possible.A helper class
To address confusion/complaints, I've written a "class" that does this abstraction (pastebin link):
This class doesn't do everything and it won't handle every conceivable use case. I'm not a library guy. But for general interactive use it should be fine.
To use this class, create an instance and point it to the element you want to associate keyboard input with:
What this will do is attach a new input listener to the element with
#txt
(let's assume it's a textarea), and set a watchpoint for the key comboCtrl+5
. When bothCtrl
and5
are down, the callback function you passed in (in this case, a function that adds"FIVE "
to the textarea) will be called. The callback is associated with the nameprint_5
, so to remove it, you simply use:To detach
input_txt
from thetxt
element:This way, garbage collection can pick up the object (
input_txt
), should it be thrown away, and you won't have an old zombie event listener left over.For thoroughness, here is a quick reference to the class's API, presented in C/Java style so you know what they return and what arguments they expect.
Update 2017-12-02 In response to a request to publish this to github, I have created a gist.
Update 2018-07-21 I've been playing with declarative style programming for a while, and this way is now my personal favorite: fiddle, pastebin
Generally, it'll work with the cases you would realistically want (ctrl, alt, shift), but if you need to hit, say,
a+w
at the same time, it wouldn't be too difficult to "combine" the approaches into a multi-key-lookup.I hope this
thoroughly explained answermini-blog was helpful :)您应该使用 keydown 事件来跟踪按下的按键,您应该使用 keyup 事件来跟踪按下按键的时间。释放。
请参阅此示例: http://jsfiddle.net/vor0nwe/mkHsU/
(更新:我在此处复制代码,万一 jsfiddle.net 保释:)
HTML:
...和 Javascript(使用 jQuery):
在该示例中,我使用一个数组来跟踪按下的键。在真实的应用程序中,您可能希望在释放每个元素的关联键后
删除
每个元素。请注意,虽然在本例中我使用 jQuery 来让事情变得简单,但这个概念在“原始”Javascript 中工作时也同样有效。
You should use the keydown event to keep track of the keys pressed, and you should use the keyup event to keep track of when the keys are released.
See this example: http://jsfiddle.net/vor0nwe/mkHsU/
(Update: I’m reproducing the code here, in case jsfiddle.net bails:)
The HTML:
...and the Javascript (using jQuery):
In that example, I’m using an array to keep track of which keys are being pressed. In a real application, you might want to
delete
each element once their associated key has been released.Note that while I've used jQuery to make things easy for myself in this example, the concept works just as well when working in 'raw' Javascript.
对于需要完整示例代码的人。添加右+左
for who needs complete example code. Right+Left added
这不是通用方法,但在某些情况下很有用。它对于 CTRL + something 或 Shift + something 或 CTRL + 等组合很有用Shift + something 等。
示例:当您想使用 CTRL + P 打印页面时,第一个键按下的总是 CTRL 后跟 P。与 CTRL + S、CTRL + U 和其他组合相同。
This is not a universal method, but it's usefull in some cases. It's usefull for combinations like CTRL + something or Shift + something or CTRL + Shift + something, etc.
Example: When you want to print a page using CTRL + P, first key pressed is always CTRL followed by P. Same with CTRL + S, CTRL + U and other combinations.
我用这种方式(必须检查 Shift + Ctrl 按下的位置):
I used this way (had to check wherever is Shift + Ctrl pressed):
我喜欢使用这个片段,它对于编写游戏输入脚本非常有用
I like to use this snippet, its very useful for writing game input scripts
这是 Bradens 答案的实现。
Here's an implementation of Bradens answer.
使按键甚至调用多个函数,每个函数检查特定的键并做出适当的响应。
Make the keydown even call multiple functions, with each function checking for a specific key and responding appropriately.
我会尝试在
keydown
上添加一个keypress
Event
处理程序。例如:这只是为了说明一种模式;我不会在这里详细介绍(特别是不涉及浏览器特定的 level2+
Event
注册)。请回帖无论这是否有帮助。
I'd try adding a
keypress
Event
handler uponkeydown
. E.g:This is just meant to illustrate a pattern; I won't go into detail here (especially not into browser specific level2+
Event
registration).Post back please whether this helps or not.
如果按下的键之一是 Alt / Crtl / Shift 您可以使用此方法:
If one of keys pressed is Alt / Crtl / Shift you can use this method:
如果有人需要简单的解决方案。
If someone needs easy solution.
我知道这不是最好的方法。
Not the best way, I know.
如果你想找到任何带有控制键的按键事件,你可以这样做
if you want to find any keypress event with control key you can do like this
只是让东西更稳定:
Just making something more stable :
对于使用 React 的用户,这是我的解决方案:
请记住,我们需要在
useEffect
函数中使用backdropOpenLocal
而不是backdropOpen
,因为我们只想更新局部作用域变量并保留作用域的状态。如果我们更新Example组件的状态并尝试访问
backdropOpen
,我们将获得与之前相同的值,除非我们在<的依赖项数组中传入backdropOpen
代码>useEffect;这将导致useEffect
内的作用域变量被重置,而我们不希望出现这种情况。For whoever is using React, here is my solution:
Keep in mind that we need to use the
backdropOpenLocal
instead ofbackdropOpen
inside theuseEffect
function, because we want to update the local scoped variable only and keep the state of the scope.If we update the state of the Example component and try to access
backdropOpen
, we will have the same value as before, unless we pass in thebackdropOpen
in the dependency array ofuseEffect
; this would cause the scoped variables insideuseEffect
to be reset, and we don't want that.我使用案例、if 和 bool。我有一个项目,这对我来说非常有用
||更新||
我制作了一个包含关键变量的库,这里是如何使用它:
这是一个例子:
就是这样,你可以将它放在你的项目中,有点像jquery,这也需要jquery,这里是:
i use cases, ifs and bools. I had a project and this worked great for me
||UPDATE||
I made a library that includes a key variable, here is how to use it:
and here is an example:
that's it, you can put it inside of your projects kinda like jquery, this also needs jquery, here it is:
您可以使用
keydown
添加它们的键并删除它们或在keyup
上将它们设置为 false :您可以这样检查:
每当您执行 keyup 时,它都会将其设置为 false 。
You Can Add They Keys using
keydown
and remove them or set them to false onkeyup
:you can check like that:
and when ever you do keyup it will set it to false.