[英]Detect key press event that isn't “enter” in JavaScript
I want to detect when the user pressed a key that's not the "enter" button. 我想检测用户何时按下了不是“输入”按钮的键。 For example: if the user pressed the "shift" key it will do something.
例如:如果用户按下“ Shift”键,它将执行某些操作。 I have this code but it's not working:
我有以下代码,但无法正常工作:
$(document).keypress(function(e) {
var keycode = (e.keyCode ? e.keyCode : e.which);
if (keycode!= '13) {
//do somthing
}
});
KeyboardEvent.keyCode
and KeyboardEvent.which
are both deprecated (confusing, I know). 不推荐使用
KeyboardEvent.keyCode
和KeyboardEvent.which
(我知道这令人困惑)。 Use KeyboardEvent.code
like so: 像这样使用
KeyboardEvent.code
:
$(document).keypress(function(e){
if(e.code !== "Enter"){
// Your code here
}
});
Try 尝试
<html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script type="text/javascript"> $(function() { document.onkeydown = function(e) { if (!e.shiftKey) { alert("You have entered a key that was not shift"); } }; }); </script> </head> <body> Please try to enter a key. </body> </html>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.