简体   繁体   English

Keydown不适用于我的eventlistener

[英]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.

相关问题 EventListener keydown正在工作,但keyup不起作用 - EventListener keydown is working but keyup isn't 我的EventListener无法正常工作 - my EventListener are not working Javascript eventListener keydown无法正常工作我点击 - Javascript eventListener keydown not working EVERY time I click JavaScript:除非我先单击实际按钮,否则“keydown”事件监听器不起作用? - JavaScript: “keydown” EventListener not working unless I click on the actual button first? IE7 中的 keydown 事件监听器 - keydown EventListener in IE7 打字稿:requestAnimationFrame和eventlistener:keyup / keydown - typescript: requestAnimationFrame and eventlistener:keyup/keydown keydown 的事件监听器无法正常工作 - Eventlistener for keydown does not work properly 我正在尝试在空格键上为 keydown eventListener 触发事件,它将在数组中显示随机单词。 如果条件语句不起作用 - I am trying to have event trigger on spacebar for a keydown eventListener that will display random word in array. If conditional statement not working 为什么我的jQuery keydown功能仅适用于第一个输入元素 - Why is my jQuery keydown feature only working on the first input element 为什么我的 innerHTML 更改颜色不适用于 javascript 按键? - Why is my innerHTML change colour not working with javascript keydown?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM