CTRL keyCode(17)无法在JavaScript中运行? [英] CTRL keyCode (17) not working in JavaScript?
问题描述
我有以下代码,它将eventListener添加到HTML textarea。它应该控制日志按下的键码,如果keyCode是==到17(CTRL),控制台日志你按下了CTRL。。出于某种原因,当我在textarea中按CTRL时,它不是控制台记录按下的keyCode,也不是你按下了CTRL。如果我按A例如,控制台日志返回97这是正确的。它也适用于所有其他字母。
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.
以下是代码:
document.getElementById("msgBox").addEventListener("keypress",function(e){
console.log(e.keyCode);
if(e.keyCode == 17){
console.log("You pressed CTRL.");
}
});
我做错了什么?
更新:它也没有使用其他特殊键,如shift,Fx,alt,home等。
UPDATE : It's also not working with other special keys like "shift, Fx, alt, home etc.
textarea的HTML:
HTML for the textarea :
<textarea id="msgBox" placeholder="Enter your message" autofocus></textarea>
推荐答案
出于某种原因,特殊键不适用于 keypress
事件,但他们使用 keydown
事件。
For some reason, special keys do not work with the keypress
event, but they do with the keydown
event.
这篇关于CTRL keyCode(17)无法在JavaScript中运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!