在Javascript中,如何判断用户是否同时按两个键? [英] In Javascript, how do I tell if a user is pressing two keys at the same time?
问题描述
在Javascript中,如何判断用户是否同时按两个键?
In Javascript, how do I tell if a user is pressing two keys at the same time?
例如,我在屏幕。当用户按住向右箭头,用户按住向上箭头并向右移动时,我想将其移动。那部分工作很简单。如果用户持有向上和向右箭头,我想要沿着对角线向右移动圆圈。
For example, I have drawn a circle in the middle of the screen. I want to move it up while the user holds down the up arrow and right while the user holds down the right arrow. That part works easy. If user holds both the up and right arrows, I want to move the circle diagonally, up and to the right.
它不像这样可能与基本的Javascript事件处理,但肯定有人已经弄清楚了一个工作/黑客/改进。
It doesn't look like this possible with basic Javascript event handling, but surely someone has figured out a work around/hack/improvement.
推荐答案
这是你需要做的概念(我猜这是伪代码):
Here is what you need to do conceptually (I guess this is called pseudo code):
从这样开始:
var PIXEL_DELTA = 10; // Distance to move in pixels
var leftPressed = 0,
upPressed = 0,
downPressed = 0,
rightPressed = 0;
然后在每个 keydown
事件中,测试是否按下的是 left
, up
等,并将其变量从 0
到 PIXEL_DELTA
。
Then on every keydown
event, test if it the key pressed is left
, up
, etc and turn its variable from 0
to PIXEL_DELTA
.
每个 keyup
事件,运行相同的测试并将正确的变量返回到 0
。
On every keyup
event, run the same test and turn the correct variable back to 0
.
然后,在你的移动代码(实际代码):(这个代码改编自Crescent Fresh的很棒的例子):
Then, in your moving code (real code): (This code adapted from Crescent Fresh's awesome example):
function move() {
var dot = document.getElementById('dot'),
deltaX = rightPressed - leftPressed,
deltaY = downPressed - upPressed;
if(deltaX) {
dot.style.left = (parseInt(dot.style.left, 10) || 0) + deltaX + 'px';
}
if (deltaY) {
dot.style.top = (parseInt(dot.style.top, 10) || 0) + deltaY + 'px';
}
}
浏览器将(应该)单独触发 keydown
/ keyup
每个键的事件,即使它们同时被按下。
The browser will (should) fire a separate keydown
/keyup
event for each key, even if they are "simultaneously" pressed.
工作实例
Crescent Fresh将一个 JSBin的完整示例。请务必访问可编辑版本,并使用代码。
Crescent Fresh put together a full example on JSBin. Be sure to visit the editable version as well to play with the code.
这篇关于在Javascript中,如何判断用户是否同时按两个键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!