首页 > 解决方案 > 当我将 EventListener 从“click”更改为“keydown”时,代码停止工作

问题描述

当您单击它(在网格上)时,下面的代码成功地改变了网格中块的位置。

但是,当我按下一个键时,我打算这样做。碰巧的是,当我将 EventListener 从“click”更改为“keydown”时,如果在运行脚本时按下笔记本电脑的任何键,我将没有响应。

我认为元素有问题(我需要关注它?如何?),或者文档不知何故无法识别键输入。我能做些什么来尝试解决这个问题?

let x = 5;
let y = 5;

function CreateSnake(){
  tabuleiro.appendChild(snake);
   snake.style.gridColumnStart = x;
   snake.style.gridRowStart = y;

   snake.classList.add("snake");
  };

  tabuleiro.addEventListener("click" , function(){
      moveSnakeRight();
      remove()
    });

function moveSnakeRight(){
  if ( x < 10)
  console.log(x++)
;
}

function remove(){
  snake.remove()
}

标签: addeventlistenerkeydownonkeydown

解决方案


我的猜测是您keydown在错误的元素上设置了事件侦听器。为了处理keydown事件,元素必须能够接收焦点(设置tabindex)。请参阅以下演示:https ://jsfiddle.net/mqe59dL6/

const noFocus = document.getElementById('noFocus');
const focus = document.getElementById('focus');

function handler(event) {
    event.cancelBubble = true;
    console.log(event.target.id || 'document', event.keyCode);
}

noFocus.addEventListener('keydown', handler);
focus.addEventListener('keydown', handler);
document.addEventListener('keydown', handler);
#noFocus {
  height: 60px;
  background-color: #aff;
  padding: 10px;
}

#focus {
  height: 60px;
  background-color: #faf;
  padding: 10px;
}
<div id="noFocus">
  I can't receive focus. Events will go to the document.
</div>
<div id="focus" tabindex="0">
  I can receive focus, click on me first.
</div>

另一种方法是改为处理事件document。试试document.addEventListener("keydown", ...)


推荐阅读