Html addEventListener 按键不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15647810/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 06:53:00  来源:igfitidea点击:

addEventListener keydown not working

javascripthtmlhtml5-canvas

提问by JBurace

I took some basic Pong code available on the internet and tried to add keypresses, the code is here: http://cssdeck.com/labs/ping-pong-game-tutorial-with-html5-canvas-and-sounds

我在互联网上获取了一些基本的 Pong 代码并尝试添加按键,代码在这里:http: //cssdeck.com/labs/ping-pong-game-tutorial-with-html5-canvas-and-sounds

I added this:

我加了这个:

canvas.addEventListener("keydown", handlekeydown, true);

After this existing code:

在此现有代码之后:

canvas.addEventListener("mousemove", trackPosition, true);
canvas.addEventListener("mousedown", btnClick, true);

And I also added this:

我还添加了这个:

function handlekeydown(e) {
  console.log("debug");
  console.log("keycode: "+e.keyCode);
}

But the function is never called even though I try pressing various keys. Why is this? I'm pretty sure the Canvas is in focus.

但是即使我尝试按下各种键,也永远不会调用该函数。为什么是这样?我很确定 Canvas 是焦点。

回答by Jean Louren?o

You can't assign the keydownevent to the canvas because you can't focus the canvas with the cursor. You will need to assign the event to the window:

您无法将keydown事件分配给画布,因为您无法使用光标聚焦画布。您需要将事件分配给窗口:

window.addEventListener("keydown", handle, true);

回答by metalwings

You can try to replace canvaswith window.

您可以尝试用window替换canvas

回答by Kinematic

I agree with the first floor, but you can try to do this. As follows:

我同意一楼的观点,但你可以尝试这样做。如下:

//set attribute tabindex = 0 (other number), ensure the canvas in the focus sequence
//like this, you can focus canvas
//http://www.w3schools.com/tags/att_global_tabindex.asp
<canvas id="snake" width="400" height="600" tabindex=0 > </canvas> 

//then register keydown event
document.getElementById("snake").addEventListener("keydown", function(ev){
          console.log(ev);
}, true);