CTRL keyCode (17) not working in JavaScript?

怎甘沉沦 提交于 2020-01-17 05:32:13

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!