capturing document level keypress events with java

2019-07-20 12:37发布

问题:

i've been trying to capture document level key press events in a webpage but

$(document).bind('keydown', 'a', keyevent_cb);

fails to respond consistently in firefox. works great in IE (which is kind of a trip). any recommendations? i've attempted other solutions without jquery and they also fail for firefox.

so i'm open to any result that works consistently (jquery or not). thanks in advance.

回答1:

The following attaches a keypress event listener to the body element:

$("body").on("keypress", function (e) {
    // logic for key event here
});

With your keyevent_cb callback, you could simply do:

$("body").on("keypress", keyevent_cb);


回答2:

$(document).keypress(function(e)
{
    switch(e.which)
    {
        // user presses the "a"
        case 97: doSomething(); break;
    }
});