[英]Keydown not working for my eventlistener
I am confused as to why when I press a key, my function is not logging the keydown event? 我很困惑为什么当我按下一个键时,我的功能是不记录keydown事件?
window.addEventListener('keydown', function(e) { console.log(e); });
<h1> Start typing </h1>
I believe that the right approach has to be use the document object and not the window object. 我认为正确的方法必须是使用文档对象而不是窗口对象。
A code like the following should work: 像下面这样的代码应该有效:
document.addEventListener('keydown', function(e) {
console.log("event", e);
});
Your snippet seems to be okay. 你的片段似乎没问题。 So it might have to do with the surrounding environment, where you run it. 因此,它可能与您运行它的周围环境有关。
(That is, if the other answers using document
did not already help you.) (也就是说,如果使用document
的其他答案对您没有帮助。)
Please investigate the situation where it fails. 请调查失败的情况。 A possible reason could be that the keyEvent
is cancelled by any EventListener along the bubble way. 可能的原因可能是任何EventListener沿着冒泡方式取消了keyEvent
。
You are fetching the keydown
at the top-most level, the window level (even higher than the document level). 您正在获取最顶层级别的keydown
,即窗口级别(甚至高于文档级别)。
If the bubbling is stopped along the event way, you won't see it. 如果沿事件方式停止冒泡,您将看不到它。
Try for example 试试这个例子
document.addEventListener("keydown", function(e) {
e.stopPropagation();
});
This will also prevent you from seeing the keydown in your orignal event listener. 这也会阻止您在orignal事件侦听器中看到keydown。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.