addeventlistener - 当我将 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()
}
解决方案
我的猜测是您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", ...)
。
推荐阅读
- python - Python - 如何验证一个非常大的 JSON 文件?
- c++ - 在 ifstream 上调用 clear() 是否有问题?
- flask - 手动调用烧瓶 socketio 事件处理程序
- java - Spring JPA Criteria API 本机查询与连接给出 org.springframework.orm.jpa.JpaSystemException
- git - 找到了一个使用 TFS(集中式)管理的旧解决方案 - 很容易进入 git?
- android-studio - 当您在代码中添加 java 注释块时,如何阻止 Android Studio 删除导入?
- javascript - 如何解析带有前导不可打印控制字符的 URL?
- r - 重复的 POSIXct 结果 - 随着时间的推移聚合?
- android - Android 应用程序链接到动态功能显示应用程序选择器对话框两次显示相同的应用程序
- python - pyinstaller、多处理和 QT5 的组合导致新的 GUI 窗口和崩溃