简体   繁体   English

画布-addEventListener无法模拟按键

[英]Canvas - addEventListener not working simulating keypress

I have the below addEventListener in one canvas game to control the keyboard events: 我在一个画布游戏中具有以下addEventListener来控制键盘事件:

document.addEventListener("keydown", keyDown, true);
document.addEventListener("keypress", keyPress, true); 

And the below jQuery code that simulate the keypress event to start the game. 下面的jQuery代码模拟了启动游戏的按键事件。

$("#new").click(function(event) {
  event.preventDefault(); // Stop the link click from doing anything.
  var ev = jQuery.Event("keypress"); // Build an event to simulate keypress.
  ev.which = 78; // Keycode for 'N' is 68
  ev.ctrlKey = false; // Control key is down.
  $(this).trigger(ev); // Fire!
});

If I press 'N' with my keyboard the canvas game is starting correctly, but when I click the #new div nothing happens. 如果我用键盘按“ N”键,则画布游戏将正确启动,但是当我单击#new div时,什么也不会发生。

My canvas element: 我的画布元素:

<canvas width="500px" height="480px" tabindex="1" id="game"></canvas>

jQuery .trigger only runs events bound using jQuery, not addEventListener. jQuery .trigger仅运行使用jQuery绑定的事件,而不运行addEventListener。

You need to use 您需要使用

$(document).bind('keydown',function(){

or 要么

$(document).keydown(function(){

to be able to use jQuery trigger . 能够使用jQuery trigger All or nothing jQuery. 全有或全无jQuery。

Alternatively, you could use native dispatchEvent , but that's complicated, messy and not jQuery. 另外,您可以使用本机dispatchEvent ,但这很复杂,杂乱而不是jQuery。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM