如何在 JavaScript 中的按键上捕获 ALT+N

How to capture ALT+N on keypress in JavaScript

我有一些简单的代码可以记录按下的键代码,如下所示:

window.addEventListener('keypress', function(e) {
  console.log(e.keyCode);
})

它似乎适用于 Alt + 我键盘上几乎所有其他键盘。 除了 Alt + N. 它似乎根本没有注册事件!只是 N(没有 Alt)似乎有效,其他组合如 Ctrl + N。当我键入 Alt + N 时,没有其他任何反应,所以据我所知,它没有被系统保留。我在 Mac.

上使用 Chrome

这只是我的电脑有问题还是其他人也会这样?如果它确实发生在其他人身上,为什么会这样,有没有办法检测到它?

尝试:

window.addEventListener('keydown', function(e) {
  if (e.altKey == true && e.keyCode == 78)
    console.log('Alt + N'); 
});

使用 keypress 事件对我来说对 Alt+N 以及与 [=33 的任何组合不起作用=]Alt 就此而言。有些组合可以与 Ctrl 一起使用,有些则不能。

但是,当我监听 keydownkeyup 事件时,我能够记录这些事件。所以,我想你可以在 Alt 上监听 keydown 事件,如果之前 N 有一个 keydown 事件Alt 生成 keyup,您已成功检测到 Alt+N 组合。

不过我不确定为什么会这样。

编辑

根据Mozilla documentation,

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.

至于为什么有些快捷方式在 Chrome 中有效,而有些则无效,Mozilla

Chrome does not fire the keypress event for known keyboard shortcuts. Which keyboard shortcuts are known depends on the user's system. Use the keydown event to implement keyboard shortcuts.