Javascript 'keydown' 事件侦听器不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18928116/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript 'keydown' event listener is not working
提问by user1668814
The mousemove event works and calls onMouseMove each time I move on the canvas. Although, the keydown and keyup events never work. I click on the canvas and hit some keys, but no event is triggered. Does anyone know why the events are not working? Thank you for any advice! I'm following the html5 course on udacity if anyone is curious where the code came from.
每次我在画布上移动时, mousemove 事件都会起作用并调用 onMouseMove 。虽然, keydown 和 keyup 事件永远不会起作用。我点击画布并按下了一些键,但没有触发任何事件。有谁知道为什么这些事件不起作用?感谢您的任何建议!如果有人好奇代码的来源,我正在关注 udacity 的 html5 课程。
InputEngineClass = Class.extend({
keyState: new Array(),
setup: function() {
document.getElementById("gameCanvas").addEventListener('mousemove', gInputEngine.onMouseMove);
document.getElementById("gameCanvas").addEventListener('keydown', gInputEngine.onKeyDown);
document.getElementById("gameCanvas").addEventListener('keyup', gInputEngine.onKeyUp);
},
onMouseMove: function (event) {
console.log("Called onMouseMove");
var posx = event.clientX;
var posy = event.clientY;
},
onKeyDown: function (event) {
console.log("KEY DOWN!!!");
keyState[event.keyID] = true;
gInputEngine.update();
},
onKeyUp: function (event) {
console.log("KEY UP!!!");
keyState[event.keyID] = true;
},
update: function() {
KeyW = 87;
if(gInputEngine.keyState[KeyW]) console.log("FORWARD!!!");
}
});
gInputEngine = new InputEngineClass();
回答by jfriend00
I'll turn my comment into an answer so you can wrap up this question.
我会把我的评论变成一个答案,这样你就可以结束这个问题了。
For a DOM object to receive keyboard events, they must first be capable of getting the keyboard focus on a page. Only then will keyboard events be directed to that object. The simplest way to do that for a canvas object is to give it a tabIndex
attribute.
要让 DOM 对象接收键盘事件,它们首先必须能够获得页面上的键盘焦点。只有这样,键盘事件才会被定向到该对象。对画布对象执行此操作的最简单方法是为其指定tabIndex
属性。
canvas.setAttribute("tabindex", 0);
You can see someone else's summary of that problem here: http://www.dbp-consulting.com/tutorials/canvas/CanvasKeyEvents.html
您可以在此处查看其他人对该问题的总结:http: //www.dbp-consulting.com/tutorials/canvas/CanvasKeyEvents.html