[英]How can I get auto-repeated keydown events in Firefox when arrow keys are held down?
I've got several editable div
s. 我有几个可编辑的
div
。 I want to jump through them by pressing arrow keys (38 and 40). 我想按箭头键(38和40)跳过它们。
Firefox 3 on Mac OS and Linux won't repeat the events on holding the key. Mac OS和Linux上的Firefox 3不会重复持有密钥的事件。 Obviously only
keypress
events are supported for repetition. 显然,只有
keypress
事件才能重复。 As the keys 38 and 40 are only supported on keydown
I'm kind of stuck. 因为键38和40仅在
keydown
支持,所以我有点卡住了。
Yes, you're kind of stuck. 是的,你有点卡住了。 You could emulate the behaviour you want by using timers until you receive the corresponding
keyup
, but this obviously won't use the user's computer's keyboard repeat settings. 你可以模仿你想使用定时器行为,直到收到相应的
keyup
,但这显然不会使用用户的电脑的键盘重复设置。
The following code uses the above method. 以下代码使用上述方法。 The code you want to handle keydown events (both real and simulated) should go in
handleKeyDown
: 你想要处理keydown事件(真实和模拟)的代码应该在
handleKeyDown
:
var keyDownTimers = {};
var keyIsDown = {};
var firstKeyRepeatDelay = 1000;
var keyRepeatInterval = 100;
function handleKeyDown(keyCode) {
if (keyCode == 38) {
alert("Up");
}
}
function simpleKeyDown(evt) {
evt = evt || window.event;
var keyCode = evt.keyCode;
handleKeyDown(keyCode);
}
document.onkeydown = function(evt) {
var timer, fireKeyDown;
evt = evt || window.event;
var keyCode = evt.keyCode;
if ( keyIsDown[keyCode] ) {
// Key is already down, so repeating key events are supported by the browser
timer = keyDownTimers[keyCode];
if (timer) {
window.clearTimeout(timer);
}
keyIsDown[keyCode] = true;
handleKeyDown(keyCode);
// No need for the complicated stuff, so remove it
document.onkeydown = simpleKeyDown;
document.onkeyup = null;
} else {
// Key is not down, so set up timer
fireKeyDown = function() {
// Set up next keydown timer
keyDownTimers[keyCode] = window.setTimeout(fireKeyDown, keyRepeatInterval);
handleKeyDown(keyCode);
};
keyDownTimers[keyCode] = window.setTimeout(fireKeyDown, firstKeyRepeatDelay);
keyIsDown[keyCode] = true;
}
};
document.onkeyup = function(evt) {
evt = evt || window.event;
var keyCode = evt.keyCode;
var timer = keyDownTimers[keyCode];
if (timer) {
window.clearTimeout(timer);
}
keyIsDown[keyCode] = false;
};
You can use keypress and check the e.keyCode == 38,40 instead of e.which or e.charCode This is consistent across Mac and Win. 您可以使用按键并检查e.keyCode == 38,40而不是e.which或e.charCode这在Mac和Win中是一致的。
$('#test').bind($.browser.mozilla ? 'keypress' : 'keyup', function(e) {
if ( (e.which || e.keyCode) == 40 ) { /* doSometing() */ }
});
See JavaScript Madness: Keyboard Events (3.2. Values Returned on Character Events) and event.keyCode on MDC. 请参阅JavaScript疯狂:键盘事件 (3.2。在字符事件上返回的值)和MDC上的event.keyCode。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.