跟踪键盘键的状态(JavaScript)

时间:2017-03-09 14:26:31

标签: javascript events keyboard

我想跟踪整个键盘上所有键的keydown和keyup事件。我的想法是创建一个将其密钥代码存储为属性的类。如下所示 -



function Keyboard(){
  var self = this; // Store this object instance for the events
  this.key = {};
  
  // Events
  window.addEventListener("keydown", function(e){
    self.key["k"+e.keyCode] = true;
  });
  window.addEventListener("keyup", function(e){
    self.key["k"+e.keyCode] = false;
  });
}

Keyboard.prototype.active = function(keyCode){
  if(this.key["k"+keyCode] === true){
    return true;
  }
  else{
    return false;
  }
}


/* Testing below */
var keyboard = new Keyboard();
setInterval(function(){
  console.log("Space(keycode = 32) active: " + keyboard.active(32));
},1000 / 4);




这实际上很有效。但是将它们存储在这样的对象中似乎效率很低。有没有其他选择,你对此有何看法?

0 个答案:

没有答案