Keydown停止

时间:2016-02-04 08:31:55

标签: jquery keydown

我正在使用一个对象来记录在实例中按下的箭头键。在按住left的同时我也开始按住right,然后停止按住left我的keydown函数仍会运行,但是如果我执行相同的设置但是停止按住{{1}相反,该函数停止。

这里有以下功能:

right

有人可以解释为什么我停止按键的顺序会改变var keys = {}; $(document).keydown(function(e){ keys[e.which] = true; console.log('h'); moveBall(); }); $(document).keyup(function(e){ console.log(e.which); delete keys[e.which]; }); function moveBall(){ var vals = []; var ball = $("#ball1"); var up = false; var down = false; var left = false; var right = false; for( var key in keys ) { if ( keys.hasOwnProperty(key) ) { vals.push(key); } } if ($.inArray("39", vals)> -1) right = true; // Right if ($.inArray("37", vals)> -1) left = true; if ($.inArray("38", vals)> -1) up = true; if ($.inArray("40", vals)> -1) down = true; } 功能是否仍在运行?

1 个答案:

答案 0 :(得分:3)

所以,你试图循​​环播放" moveBall"所以动作取决于按下哪个键。

我会稍微改变你的逻辑。

//Global object for what keys are active right now.

var keysBeingPressed = {
    right: false,
    left: false,
    up: false,
    down: false
};

$(document).keydown(function(e){
    // Set the right direction = true
    if (e.which == "39") keysBeingPressed.right = true;
    if (e.which == "37") keysBeingPressed.left = true;
    if (e.which == "38") keysBeingPressed.up = true;
    if (e.which == "40") keysBeingPressed.down = true;
});

$(document).keyup(function(e){
    // Set the right direction = false
    if (e.which == "39") keysBeingPressed.right = false;
    if (e.which == "37") keysBeingPressed.left = false;
    if (e.which == "38") keysBeingPressed.up = false;
    if (e.which == "40") keysBeingPressed.down = false;
});



function moveBall(){
    var ball = $("#ball1");

    // Going left is decreasing X, right is increasing X.
    // Going up is decreasing Y, down increases Y.
    // So, up+left, is diagonal, you move x and y both..
    var movement = {
        x: 0,
        y: 0
    }

    if(keysBeingPressed.right) movement.x++;
    if(keysBeingPressed.left) movement.x--;  //If left+right; x = 1 - 1 = 0 so no movement.
    if(keysBeingPressed.up) movement.y--;
    if(keysBeingPressed.down) movement.y++;

    // add your movement in x/y to top/left
    ball.css({
        top: "+="+movement.y,  //+= adds the value
        left: "+="+movement.x
    });
}

// Loop this function, you want it to run every "animation frame"
setInterval(function(){
    moveBall();
}, 10);

添加了移动球的代码。