Javascript "keydown" 多键无法正常工作

Javascript "keydown" with mutiple key wont work properly

我正在制作一个键盘映射器(它基本上允许我们检查同时按下的多个键),但我遇到了一个问题。

问题是它无法检测到所有被按下的键。例如:we pressed 10 keys but the code says that only 7 keys are being pressed,例如 we pressed 6 keys but the code says that only 4 keys are being pressed,是的,它非常随机...

那么解决方法是什么?

注意:

  1. 我已经尝试过addEventListener和其他方法
  2. 我已经尝试过其他人制作的键盘映射器,但他们都有同样的问题(至少我遇到过的)
  3. 我愿意接受其他方法(除了这个)
  4. 我是新手所以...是的 :p

谢谢!

代码如下:

var obj = {};
$(document).ready(function() {
  
  document.addEventListener("keydown", function(event) {
    obj[event.keyCode] = true;
    $("#output").text("" + JSON.stringify(obj));
  });
  
  $(document).keyup(function() {   
    obj[event.keyCode] = false;
    $("#output").text("" + JSON.stringify(obj));   
  });

});
<!DOCTYPE HTML>
<html>

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
  <link href="style.css" rel="stylesheet" type="text/css">
</head>

<body>
  <p>"PRESS ANY KEY"</p>
  <p>KeyDown:
    <p id="output"></p>
  </p>
  <br/>
</body>

</html>

问题不在于 JavaScript,而在于键盘本身。它被称为键盘重影,并且有一个 great article from Microsoft itself 解释它。

"Ghosting" is the problem that some keyboard keys don't work when multiple keys are pressed simultaneously. The key presses that don't show up on the computer or seem to have disappeared are said to have been "ghosted". On most keyboards, even some that are explicitly marketed as "Anti-Ghosting," this happens with many three key combinations. Imagine playing your favorite video game and not being able to, say, run diagonally and fire your weapon at the same time (say pressing a, w, and g simultaneously). This is a result of the internal design of most existing keyboards, as will be explained below.

您的代码是正确的,可以与多按键识别键盘一起使用。