admin管理员组文章数量:1415137
I'm trying to make a script to detect if a certain key is being pressed, but the only reasonable thing I could think of was this.
onkeydown('F12'){
myFunction()
}
How would I do this? Thanks!
I'm trying to make a script to detect if a certain key is being pressed, but the only reasonable thing I could think of was this.
onkeydown('F12'){
myFunction()
}
How would I do this? Thanks!
Share Improve this question asked Jun 11, 2020 at 0:44 WestlenandoWestlenando 882 silver badges9 bronze badges 1- 3 Does this answer your question? Simplest way to detect keypresses in javascript – Brian McCutchon Commented Jun 11, 2020 at 0:47
4 Answers
Reset to default 3You should listen for the keydown
event and check its e.key
property:
const KEY_HANDLERS = {
F1: () => console.log('You pressed F1.'),
ArrowUp: () => console.log('You pressed ↑.'),
KeyA: () => console.log('You pressed A.'),
};
document.addEventListener('keydown', (e) => {
e.preventDefault();
const handler = KEY_HANDLERS[e.code];
if (handler) {
handler();
return;
}
console.log('Pressed a key without a handler.')
});
If you need to check KeyboardEvent's properties values such as e.key
, e.code
, e.which
or e.keyCode
, you can use https://keyjs.dev:
Disclaimer: I'm the author.
using keyCode you can get the specific key. This example works if you press enter keyword (code 13). Check this out: https://keycode.info/
document.addEventListener("keypress", function(event) {
if (event.keyCode == 13) {
console.log('Hello world');
}
});
Add an event listener for the "keydown" (or "keyup") action. To get the specific key that was pressed use "event.key".
document.addEventListener("keydown", function(e){
var key = e.key
})
Maybe this is what you are looking for:
var inputForm = document.getElementById("taskInput");
inputForm.addEventListener('keydown', function(event) {
console.log("You are pressing this key :", String.fromCharCode(event.keyCode));
});
<input type="text" id="taskInput"/>
本文标签: javascriptHow to detect if a certain key is being pressedStack Overflow
版权声明:本文标题:javascript - How to detect if a certain key is being pressed - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745197259a2647202.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论