JavaScript多重按键 [英] JavaScript multiple keydown
本文介绍了JavaScript多重按键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
首先,我要感谢大家的帮助和答复.
First, I would like to thank all for your help and replies.
我正在开发一个项目,要求用户按下一个键并按住它,它将触发一个动作.
I'm working on a project that required users to press a key and hold it, it will trigger an action.
当用户按下另一个键(仍然按住第一个键)时,它将触发另一个动作.
When the user presses another key ( still holing the first key), it will trigger another action.
但是,我一直无法让JavaScript识别同时按下的两个键.
However, I'm stuck getting JavaScript to recognize two keys being pressed at the same time.
var down = false;
var keys;
document.addEventListener("keydown", function (e) {
if (down) {return;}
down = true;
keys = (keys || []);
keys[e.keyCode]=true;
if (keys[87]){
console.log("1");
}
else if (keys[83]){
console.log("2");
}
else if (keys[83] && keys[87]){
console.log("sucessfull");
}
} , false);
document.addEventListener("keyup", function (e) {
down = false;
keys[e.keyCode]=false;
stop();
}, false);
<button id="up" onmousedown="Drive(1)" onmouseup="Drive(2)">UP </button>
推荐答案
- 删除了向下"变量检查
- 删除了鼠标按钮元素-似乎与您的问题无关?
- 删除了多余的HTML正文
-
摆脱了其他分支,因为在到达&&&之前,它会被满足(87或83).条件
- Removed the 'down' variable checks
- Removed the mouse button element thing - didn't seem relevant to your problem?
- Removed the extra HTML body
Got rid of the else branching as it would be satisfied (by 87 or 83) before ever getting to the && condition
var keys;
document.addEventListener("keydown", function (e) {
keys = (keys || []);
keys[e.keyCode]=true;
if (keys[87]){
console.log("1");
}
if (keys[83]){
console.log("2");
}
if (keys[83] && keys[87]){
console.log("sucessfull");
}
} , false);
document.addEventListener("keyup", function (e) {
keys[e.keyCode]=false;
stop();
}, false);
这篇关于JavaScript多重按键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文