addEventListener keydown不工作 [英] addEventListener keydown not working

查看:1745
本文介绍了addEventListener keydown不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我添加了这个:

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

在此现有代码之后:

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

我还添加了这个:

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.

推荐答案

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

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

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

这篇关于addEventListener keydown不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆