jQuery键盘事件处理程序按住

时间:2013-10-29 18:33:13

标签: jquery event-handling keyboard

我想为游戏创建一个简单的事件处理程序,这是我的代码

     $(document).keydown(function(e){
      switch(e.keyCode){
        case 65: //left (a)

          console.log('left');
          break;

        case 68: //right (d)

          console.log('right');
          break;

      }
    });
问题是,如果我按住某个键,稍微触发一次。 我该如何防止这种行为?我在谷歌浏览器上运行我的代码

2 个答案:

答案 0 :(得分:8)

这是关键的重复。如果您愿意,可以通过记住您已经知道密钥已关闭来打败它:

// A map to remember in
var keysdown = {};

// keydown handler
$(document).keydown(function(e){

  // Do we already know it's down?
  if (keysdown[e.keyCode]) {
      // Ignore it
      return;
  }

  // Remember it's down
  keysdown[e.keyCode] = true;

  // Do our thing
  switch(e.keyCode){
    case 65: //left (a)

      console.log('left');
      break;

    case 68: //right (d)

      console.log('right');
      break;

  }
});

// keyup handler
$(document).keyup(function(e){
  // Remove this key from the map
  delete keysdown[e.keyCode];
});

旁注:我认为当您使用jQuery时,e.which是更可靠的属性,it's normalized for you by jQuery

答案 1 :(得分:2)

var keyPressed = false;

$(document).on('keydown', function(e) {
  var key;
  if (keyPressed === false) {
    keyPressed = true;
    key = String.fromCharCode(e.keyCode);

    //this is where you map your key
    if (key === 'X') {
      console.log(key);
      //or some other code
    }
  }
  $(this).on('keyup', function() {
    if (keyPressed === true) {
      keyPressed = false;
      console.log('Key no longer held down');
      //or some other code
    }
  });
});