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
Add a ment  | 

4 Answers 4

Reset to default 3

You 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