简体   繁体   English

如何检查键盘上是否释放了特定键?

[英]How do I check if a specific key was released on keyboard?

I want to check whether the escape key has been pressed/released in javascript. 我想检查是否已在javascript中按下/释放了转义键。

They way I've seen is this : 我见过的他们是这样的:

document.addEventListener('keyup', function(event) {
   //returns a number for key  
  console.log(event.keyCode);   
});

However when I went onto Mozilla it says the '.keyCode' is being deprecated use '.key' instead. 但是,当我进入Mozilla时,它说“ .keyCode”已被弃用,请改用“ .key”。 Which I did but when I changed the code to this: 我做了什么,但是当我将代码更改为此时:

document.addEventListener('keyup', function(event) {
   //returns a number for key  
  console.log(event.key);   
});

It wouldn't work it said in the console 'undefined'. 在控制台“未定义”中说这行不通。 Any ideas why? 有什么想法吗?

Also is Mozilla the best place to go, because as a beginner I'm finding it difficult to understand. Mozilla也是最好的去处,因为作为初学者,我很难理解。 Thanks 谢谢

The problem is you're adding your listener to document when it should be added to window . 问题是您要将监听器添加到document ,而应将其添加到window Eg, 例如,

window.addEventListener('keyup', function(ev) {
    console.log(ev.key);
});

You need to attach the event listener to the window. 您需要将事件侦听器附加到窗口。 This may differ by browser, but it worked for me. 这可能因浏览器而异,但对我有用。

  window.addEventListener("keyup", function (event) { if(event.key === "Escape"){ console.log("Escape was released."); } // Consume the event for suppressing "double action". event.preventDefault(); }, true); 

Try it on CodePen! 在CodePen上尝试!

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

相关问题 在JavaScript中释放键时如何停止声音 - how do i stop a sound when a key is released in JavaScript 如果 object 未定义,如何检查特定键是否未定义? - How do I check if a specific key is undefined if the object is undefined? 使用KeyUp,如何在释放回车键后获取值? - Using KeyUp, how do I get a value after the enter key is released? 在按下另一个键之后,移位键被忽略,移位键不好。如何检测何时发布? - the shift key is just ignored after another key has been depressed, poor shift key. How do I detect when it is released? 我按键盘上的ENTER键,页面刷新。 如何防止这种情况,仍然使用键盘进行搜索? - I hit the ENTER key on keyboard and page refreshes. How do I prevent this and still use the keyboard to search? 如何检查特定服务器中的角色? - How do I check for a role in a specific server? 如何检查一个键(在键盘上)是否被按住? - How to check if a key (on the keyboard) is being held down? 如何在JavaScript中释放键时进行测试 - How would I test for when a key is released in JavaScript 如何检查输入是否为空白/非空白并执行特定操作 - How do I check if input is blank/not blank and do specific thing 如何通过按 html 列表中的特定键盘键来更改选择 - How can i change selection by pressing specific keyboard key in a html list
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM