[英]Can't get keydown / keyup to work with pointer lock / fullscreen
My problem is that I recently started to change my HTML5 webapp to use fullscreen + pointer lock instead of dragging the mouse in the window.我的问题是我最近开始将我的 HTML5 webapp 更改为使用全屏 + 指针锁定,而不是在窗口中拖动鼠标。 The app uses keyboard in addition to mouse, and everything was working fine previously.
该应用程序除了鼠标外还使用键盘,以前一切正常。 However, now I can't get any kind of keypresses to work.
但是,现在我无法使用任何类型的按键。 Pointer locked mouse works perfectly.
指针锁定鼠标完美运行。
Previously I listened to keypresses like this:以前我听过这样的按键:
document.onkeydown = handleKeyDown;
document.onkeyup = handleKeyUp;
where handleKeyDown
and Up are functions, for example:其中
handleKeyDown
和 Up 是函数,例如:
function handleKeyUp(event) {
doStuffWith(event.keyCode);
}
Now, I have added keyboard listeners right next to my mousemove
listener:现在,我在
mousemove
侦听器旁边添加了键盘侦听器:
document.addEventListener('keyup', handleKeyUp(event), false);
document.addEventListener('keydown', handleKeyDown(event), false);
where handleKey
* are the same as above, but doStuffWith
doesn't do anything.其中
handleKey
* 与上面相同,但doStuffWith
不做任何事情。 It seems to get some undefined events and nothing else.它似乎得到了一些未定义的事件,没有别的。 This is probably a fairly elementary problem, but I have a hard time solving it.
这可能是一个相当基本的问题,但我很难解决它。 Most examples and tutorials I found with Google don't use
addEventListener
but instead the old style like I used previously.我在 Google 上找到的大多数示例和教程都没有使用
addEventListener
,而是使用了我之前使用的旧样式。
I am very grateful for any help.我非常感谢任何帮助。
edit // A clarification: since events are undefined, doStuffWith
doesn't get called at all, because the execution stops when trying to read .keyCode
of undefined编辑 // 澄清:由于事件未定义,
doStuffWith
根本不会被调用,因为在尝试读取未定义的.keyCode
时执行停止
The main problem is that, according to the following MDN page, alphanumeric keys are disabled in full-screen mode:主要问题是,根据以下 MDN 页面,字母数字键在全屏模式下被禁用:
https://developer.mozilla.org/en/DOM/Using_full-screen_mode#Things_your_users_want_to_know https://developer.mozilla.org/en/DOM/Using_full-screen_mode#Things_your_users_want_to_know
There are also a couple of issues with your code.您的代码也存在一些问题。 In the the line
在该行
document.addEventListener('keyup', handleKeyUp(event), false);
... you have two problems: first, the second parameter need to be a reference to a function. ...您有两个问题:首先,第二个参数需要是对函数的引用。 It's actually a reference to
undefined
because you're calling the function immediately and passing in the result rather than passing in a function.它实际上是对
undefined
的引用,因为您是立即调用函数并传入结果而不是传入函数。 Second, in browsers that support addEventListener
, the Event
object is automatically passed into the event listener function.其次,在支持
addEventListener
的浏览器中, Event
对象会自动传递给事件监听函数。 What you want, therefore, is:因此,您想要的是:
function handleKeyUp(e) {
doStuffWith(e.keyCode);
}
document.addEventListener('keyup', handleKeyUp, false);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.