我试图开发一个JavaScript游戏引擎,我遇到了这个问题:
当我按空格键时,角色会跳跃。 当我按下→角色向右移动。
问题是,当我按右键,然后按空格键时,角色会跳跃,然后停止移动。
我使用keydown函数来按下键。如何检查是否同时按下了多个键?
我试图开发一个JavaScript游戏引擎,我遇到了这个问题:
当我按空格键时,角色会跳跃。 当我按下→角色向右移动。
问题是,当我按右键,然后按空格键时,角色会跳跃,然后停止移动。
我使用keydown函数来按下键。如何检查是否同时按下了多个键?
当前回答
我使用这种方式(必须检查按下Shift + Ctrl的地方):
// create some object to save all pressed keys
var keys = {
shift: false,
ctrl: false
};
$(document.body).keydown(function(event) {
// save status of the button 'pressed' == 'true'
if (event.keyCode == 16) {
keys["shift"] = true;
} else if (event.keyCode == 17) {
keys["ctrl"] = true;
}
if (keys["shift"] && keys["ctrl"]) {
$("#convert").trigger("click"); // or do anything else
}
});
$(document.body).keyup(function(event) {
// reset status of the button 'released' == 'false'
if (event.keyCode == 16) {
keys["shift"] = false;
} else if (event.keyCode == 17) {
keys["ctrl"] = false;
}
});
其他回答
case 65: //A
jp = 1;
setTimeout("jp = 0;", 100);
if(pj > 0) {
ABFunction();
pj = 0;
}
break;
case 66: //B
pj = 1;
setTimeout("pj = 0;", 100);
if(jp > 0) {
ABFunction();
jp = 0;
}
break;
这不是最好的方法,我知道。
谁需要完整的示例代码。左+右补充道
var keyPressed = {};
document.addEventListener('keydown', function(e) {
keyPressed[e.key + e.location] = true;
if(keyPressed.Shift1 == true && keyPressed.Control1 == true){
// Left shift+CONTROL pressed!
keyPressed = {}; // reset key map
}
if(keyPressed.Shift2 == true && keyPressed.Control2 == true){
// Right shift+CONTROL pressed!
keyPressed = {};
}
}, false);
document.addEventListener('keyup', function(e) {
keyPressed[e.key + e.location] = false;
keyPressed = {};
}, false);
如果有人需要简单的解决方案。
let keys = [];
document.addEventListener("keydown", (e) => {
keys.push(e.key);
if (keys.includes("Control") && keys.includes("o")) {
console.log("open");
}
if (keys.includes("Control") && keys.includes("s")) {
console.log("save");
}
});
// clear the keys array
document.addEventListener("keyup", () => {
keys = [];
});
这不是一个通用的方法,但在某些情况下是有用的。这是有用的组合,如CTRL + something或Shift + something或CTRL + Shift + something,等。
示例:当您想使用CTRL + P打印页面时,第一个按下的键总是CTRL + P, CTRL + S, CTRL + U和其他组合也是如此。
document.addEventListener (keydown,函数(e) { //SHIFT +某个值 如果(e.shiftKey) { 开关(e.code) { 例“钥匙”: console.log('Shift + S'); 打破; } } //CTRL + SHIFT +一些 如果(e。&& e.shiftKey){ 开关(e.code) { 例“钥匙”: console.log('CTRL + Shift + S'); 打破; } } });
如果其中一个按键是Alt / Crtl / Shift,你可以使用这个方法:
document.body.addEventListener('keydown', keysDown(actions) );
function actions() {
// do stuff here
}
// simultaneous pressing Alt + R
function keysDown (cb) {
return function (zEvent) {
if (zEvent.altKey && zEvent.code === "KeyR" ) {
return cb()
}
}
}