javascript 使用javascript捕获文档级按键事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8510470/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 03:39:37  来源:igfitidea点击:

capturing document level keypress events with javascript

javascriptjqueryajaxweb

提问by ct_

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.

无法在 Firefox 中始终如一地响应。在 IE 中效果很好(这是一种旅行)。有什么建议吗?我尝试过其他没有 jquery 的解决方案,但它们也无法用于 Firefox。

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

所以我对任何持续有效的结果(jquery 与否)持开放态度。提前致谢。

回答by Phil Klein

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

以下将按键事件侦听器附加到 body 元素:

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

With your keyevent_cbcallback, you could simply do:

通过您的keyevent_cb回调,您可以简单地执行以下操作:

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

回答by Bashwork

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