按键停止

Keydown stopping

我正在使用一个对象来记录在某个实例中按下了哪些箭头键。在按住 left 的同时,如果我随后也开始按住 right,然后停止按住 left,我的 keydown 功能仍然运行,但如果我进行相同的设置但停止按住 [=12] =] 相反,函数停止。

函数如下:

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;


}

有人可以解释为什么我停止按键时的顺序会改变 keydown 函数是否仍然运行吗?

因此,您正在尝试循环 "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);

做了添加代码来移动球。