最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - capturing document level keypress events with javascript - Stack Overflow

programmeradmin4浏览0评论

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 remendations? 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.

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 remendations? 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.

Share Improve this question edited Dec 14, 2011 at 22:19 Tim Down 325k76 gold badges460 silver badges542 bronze badges asked Dec 14, 2011 at 19:27 ct_ct_ 1,2274 gold badges21 silver badges35 bronze badges 4
  • What does keyevent_cb do? Is there the suggestion of any errors therein? – David Thomas Commented Dec 14, 2011 at 19:29
  • it's just a call back function. prints an alert box. – ct_ Commented Dec 14, 2011 at 19:32
  • Do you want to fire the callback on all keypress events or only under certain conditions? – Phil Klein Commented Dec 14, 2011 at 19:39
  • all key presses and subsequent. – ct_ Commented Dec 14, 2011 at 20:06
Add a ment  | 

2 Answers 2

Reset to default 3

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);
$(document).keypress(function(e)
{
    switch(e.which)
    {
        // user presses the "a"
        case 97: doSomething(); break;
    }
});
发布评论

评论列表(0)

  1. 暂无评论