gpt4 book ai didi

jquery - 按键停止

转载 作者:行者123 更新时间:2023-12-01 03:35:50 24 4
gpt4 key购买 nike

我正在使用一个对象来记录在实例中按下的箭头键。在按住 left 的同时,如果我也开始按住 right,然后停止按住 left,我的 keydown 功能仍然会运行,但如果我执行相同的设置,但停止按住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;


}

有人可以解释一下为什么当我停止按键时的顺序会改变 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);

确实添加了移动球的代码。

关于jquery - 按键停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35196032/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com