6

ゲーム用の単純なイベント ハンドラーを作成したいのですが、コードは次のとおりです。

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

          console.log('left');
          break;

        case 68: //right (d)

          console.log('right');
          break;

      }
    });

問題は、キーを押したままにすると、少し後に複数回トリガーされることです。どうすればこの動作を防ぐことができますか? 私はGoogle Chromeでコードを実行しています

4

2 に答える 2

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 に答える