6

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

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

          console.log('left');
          break;

        case 68: //right (d)

          console.log('right');
          break;

      }
    });

问题是,如果我按住一个键,过一会儿它就会触发多次。我怎样才能防止这种行为?我在谷歌浏览器上运行我的代码

4

2 回答 2

9

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

// 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它是更可靠的属性,因为它已由 jQuery 为您标准化

于 2013-10-29T18:36:47.297 回答
3
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
    }
  });
});
于 2015-02-19T13:57:00.510 回答