开发者

How can I get auto-repeated keydown events in Firefox when arrow keys are held down?

I've got several editable divs. I want to jump through them by pressing arrow keys (38 and 40).

Firefox 3 on Mac OS and Linux won't repeat the events on holding th开发者_Go百科e key. Obviously only keypress events are supported for repetition. As the keys 38 and 40 are only supported on keydown I'm kind of stuck.


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.

The following code uses the above method. The code you want to handle keydown events (both real and simulated) should go in 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.

$('#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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜