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