问题
I have the following code which adds an eventListener to a HTML textarea. It's supposed to console log the keycode which was pressed, and, if the keyCode is == to 17 (CTRL), console log "You pressed CTRL.". For some reason, when I press CTRL in the textarea, it's not console logging the keyCode which was pressed, nor "You pressed CTRL." If I press "A" for example, console log return "97" which is correct. It also works with all other letters.
Here's the code:
document.getElementById("msgBox").addEventListener("keypress",function(e){
console.log(e.keyCode);
if(e.keyCode == 17){
console.log("You pressed CTRL.");
}
});
What am I doing wrong?
UPDATE : It's also not working with other special keys like "shift, Fx, alt, home etc.
HTML for the textarea :
<textarea id="msgBox" placeholder="Enter your message" autofocus></textarea>
回答1:
For some reason, special keys do not work with the keypress
event, but they do with the keydown
event.
回答2:
Try this instead: (e.which == 17)
回答3:
Check for e.ctrlKey
.
See the MDN documentation at https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/ctrlKey
If you want an easy way to manage keypress you could use a dedicated library like https://dmauro.github.io/Keypress/
来源:https://stackoverflow.com/questions/32207389/ctrl-keycode-17-not-working-in-javascript