用户脚本能否识别所有键码事件 Jquery

Can all keycode events be recognized by a user-script Jquery

我正在用 Tampermonkey 构建一个用户脚本,它可以识别键码事件,当键被触发时它会执行一个功能。

例如。我想按 Enter 并且它的 keycode 是 13 所以我使用了这个代码

$(document).keypress(function(event){
var which = (event.which ? event.which : event.keyCode);
if(which == '13'){
    alert("You Pressed Enter key");
}
else if(which == '17'){
    alert("You Pressed Control key");
}
});

代码在 Enter1 下工作正常,但在 Ctrl[=32= 下不起作用] 也没有 Shift 和其他键。

我是否遗漏了什么或者不是所有关键事件都可以处理?

注意:我一直在使用this link获取我的键码并在我的脚本中使用它们。

keypress 未触发控制键。根据 Mozilla 文档的描述:

The keypress event is fired when a key that produces a character value is pressed down. Examples of keys that produce a character value are alphabetic, numeric, and punctuation keys. Examples of keys that don't produce a character value are modifier keys such as Alt, Shift, Ctrl, or Meta.

绕过的一种方法是收听 keydownkeyup 事件:

$(document).keydown(function(event) {
  var which = (event.which ? event.which : event.keyCode);
  if (which == '13') {
    alert("You Pressed Enter key");
  } else if (which == '17') {
    alert("You Pressed Control key");
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

要确定左右 ctrlaltshift 键:

$(document).keyup(function (e) {
      if (e.keyCode == 16) {
          if (e.originalEvent.location == 1)
              alert('Left SHIFT pressed.');
          else
              alert('Right SHIFT pressed.');
      } else if (e.keyCode == 17) {
          if (e.originalEvent.location == 1)
              alert('Left CTRL pressed.');
          else
              alert('Right CTRL pressed.');
      } else if (e.keyCode == 18) {
          if (e.originalEvent.location == 1)
              alert('Left ALT pressed.');
          else
              alert('Right ALT pressed.');
          e.preventDefault();
      }
});

你必须包括 jquery

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>