按下并按住时,KeyDown不会连续触发

时间:2015-03-26 13:32:47

标签: javascript jquery javascript-events keydown

我有Plunkr

这包含div,我绑定keydown事件。在按向右或向左箭头时,div应该开始移动。

这适用于所有浏览器,但当按键按住时,第一个keydown事件会立即触发(div一次移动),等待时间间隔,然后它继续前进。

所以这意味着keydown事件一旦被触发,那么浏览器也会等待检测是否有后续的keyUp事件,然后在很短的时间之后(当没有密钥时),它继续引发keydown事件。

看到问题,专注于窗口,按向右箭头按住,div应移动一次5px,然后等待,然后再继续移动

问题:有没有办法,所以我可以按住键,div应该立即开始移动,而不是等待检测后续的键盘(一次)



$(function() {
  $(window).keydown(function(e) {
    console.log(e.keyCode)
    if (e.keyCode == 39)
      move(5, 'left', $('.mover'))
    else if (e.keyCode == 37)
      move(-5, 'left', $('.mover'))
  })

})

function move(offset, direction, target) {
  console.log($(target))
  $(target).css(direction, (parseInt($(target).css(direction)) + offset) + 'px')
}

.mover {
  height: 50px;
  width: 50px;
  display: inline-block;
  background: black;
  position: absolute;
  left: 0;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class='mover'></div>
&#13;
&#13;
&#13;

5 个答案:

答案 0 :(得分:4)

我会在超时时提出建议,比如

http://codepen.io/kevrowe/pen/qEgGVO

$(function() {
  var direction,
      movingTimeout = -1;

  $(window).on('keydown', function(e) {    
    if (e.keyCode == 39) {
      direction = 'right';
    } else if (e.keyCode == 37) {
      direction = 'left';
    }  

    startMoving(direction);
  });

  function stopMoving() {
    clearTimeout(movingTimeout);
    movingTimeout = -1;
  }

  function startMoving(direction) {
    if (movingTimeout === -1) {      
      loop(direction);
    }
  }

  function loop(direction) {
    move(direction === 'left' ? -5 : 5, $('.mover'));
    movingTimeout = setTimeout(loop, 10, direction);
  }

  function move(offset, $target) {
    $target.css('left', (parseInt($target.css('left')) + offset) + 'px')
  }

  $(window).on('keyup', function(e) {    
    stopMoving();
  });
})

答案 1 :(得分:1)

当您要跟踪的密钥上发生keydown事件时,请将此信息存储在某个地图中的映射或标记中。

发生密钥事件时,请清除给定密钥的标志。

然后,在计时器上,您可以轮询键映射的状态,并移动对象以按下任何键方向。

可能有一个更好的解决方案,然后轮询,但我不知道一种方法来测试一个键是否下降而不是轮询。

在keyup上,还需要检查是否需要中断移动对象。

答案 2 :(得分:1)

一种解决方案是在循环中连续运行move函数,直到keyup发生

if (e.keyCode == 39){
  var stop = setInterval(function(){ 
    move(5, 'left', $('.mover'))
  }, 25);

  window.on("keyup", function(){
    //stop the loop
    clearInterval(stop);
    //and remove the keyup listener
    window.off("keyup", arguments.callee);
  })
} else if //etc...

答案 3 :(得分:0)

对于可能感兴趣的人,这是处理双向运动的另一种方法。例如:up + right键=“东北”方向:

const FPS       = 60;
const STEP      = 5; 
const UP_KEY    = 90; // Z
const DOWN_KEY  = 83; // S
const LEFT_KEY  = 81; // Q
const RIGHT_KEY = 68; // D

const pressedKeys = [];
let movingTimeout = null;

function handleKeyDown(e) {
  pressedKeys[e.keyCode] = true;
  switch(e.keyCode) {
    case DOWN_KEY:
    case LEFT_KEY:
    case RIGHT_KEY:
    case UP_KEY:
      e.preventDefault();
      startMoving();
  }
}

function handleKeyUp(e) {
  pressedKeys[e.keyCode] = false;
  const shouldStop = !pressedKeys[UP_KEY]
    && !pressedKeys[DOWN_KEY]
    && !pressedKeys[LEFT_KEY]
    && !pressedKeys[RIGHT_KEY]
  ;
  if(shouldStop) {
    stopMoving();
  }
}

function startMoving() {
  if(!movingTimeout){
    loop();
  }
}

function stopMoving() {
  clearTimeout(movingTimeout);
  movingTimeout = null;
}

function loop() {
  const x = pressedKeys[RIGHT_KEY] ? STEP
          : pressedKeys[LEFT_KEY] ? -STEP : 0;
  const y = pressedKeys[DOWN_KEY] ? STEP
          : pressedKeys[UP_KEY] ? -STEP : 0;
  move(x, y);
  movingTimeout = setTimeout(loop, 1000 / FPS);
}

function move(x, y) {
  // Implement you own logic here for positioning / handling collisions
  // Ex: store.dispatch({ type: "MOVE_PLAYER", x, y });
  console.log(`Moving ${x} ${y} !`);
}


window.addEventListener('keydown', e => handleKeyDown(e));
window.addEventListener('keyup', e => handleKeyUp(e));

希望这会有所帮助。

干杯!

答案 4 :(得分:0)

纯javascript

<input id="some" type="text">
var input=document.getElementById("some");
input.addEventListener("keydown",function(e){

if (e.which == 40) {
var stop = setInterval(function(){ 

 console.log("ss:");

        }, 60);
        window.addEventListener("keyup", function(){
            //stop the loop
            clearInterval(stop);
            //and remove the keyup listener
            window.removeEventListener("keyup", arguments.callee);
          })


     }


})