开发者

Cross-browser keyboard event handler

I have a keypress handler that I borrowed that used to work across browsers but now no longer works on webkit browsers. Can anyone offer suggestions how to fix?

Here is the handler:

function handleKeys(e) {
    //credit: http://santrajan.blogspot.com/2007/03/cross-browser-keyboard-handler.html
    var character;
    var evt = (e) ? e : window.event;       //IE reports window.event not arg
    if (evt.type == "keydown") {
        character = evt.keycode;
        if (character < 16 ||                    // non printables
            (character > 16 && character < 32) ||     // avoid shift
            (character > 32 && character < 41) ||     // navigation keys
            character == 46) {                   // Delete Key (Add to these if you need)
            handleNonChar(character);            // function to handle non Characters
            nonChar = true;
        } else
            nonChar = false;
    } else {                                // This is keypress
        if (nonChar) return;                // Already Handled on keydown
        character = (evt.charCode) ?
                   evt.charCode : evt.keyCode;
        if (character > 31 && character < 256)        // safari and opera
            handleChar(character);               //
    }
}

The handler is called in the pages like this:

<script>
document.onkeydown = function(e) {handleKeys(e)}
document.onkeypress = function(e) {handleKeys(e)}
var nonChar = false开发者_StackOverflow;
</script>

Thanks!

Tim


If you pair up a JS Library that will normalize the charCode/keyCode differences, and use it in conjunction with a plugin dedicated to keyboard input you should make out quite well.

I've used jQuery with HotKeys Plugin. However you can also use the shortcut keyboard handling without jQuery (which the HotKeys Plugin is based on).

I like the keyboard shortcut functionality provided by these quite much - however it should be noted that certain keyboard combinations may trigger (or the user may expect them to trigger) certain actions in a particular browser.

E.g. You can capture a [CTRL] + [A] keyboard combination, but if you block this from selecting all the text - I can see the user being quite aggravated.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜