javascript jQuery:如何监听一般键盘输入?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4455274/
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-25 13:45:10  来源:igfitidea点击:

jQuery: How do I listen for general keyboard input?

javascriptjquery

提问by AP257

I'm building a site that after the page is loaded, needs to listen for a particular keyboard string.

我正在构建一个网站,在页面加载后,需要侦听特定的键盘字符串。

The event I am interested in is actually a scanner scanning an object, but it presents to the site as keyboard input, of the form ~XXX~.

我感兴趣的事件实际上是扫描对象的扫描仪,但它以键盘输入的形式呈现给站点,形式为~XXX~

I see jQuery has a keypress()event that you can bind to a particular object.

我看到 jQuery 有一个keypress()可以绑定到特定对象的事件。

But how can I listen for general keyboard input, after $(document).ready?

但是我怎样才能听听一般的键盘输入,之后$(document).ready呢?

回答by Jacob Relkin

Try this:

试试这个:

$(function() {
   $(window).keypress(function(e) {
       var key = e.which;
       //do stuff with "key" here...
   });
});

See it in action on jsFiddle

jsFiddle上查看它的实际效果

回答by Juan Mendes

I've done this before. There are many other things to worry about besides how to handle keypress events.

我以前做过这个。除了如何处理按键事件之外,还有许多其他事情需要担心。

Your scanner probably sends the input wrapped by a start and end characters. I would create a ScanReader object that attaches to the keypress event. Once it detects the start character, it starts accumulating the presses until the end character is detected.

您的扫描仪可能会发送由开始和结束字符包装的输入。我将创建一个附加到按键事件的 ScanReader 对象。一旦检测到开始字符,它就会开始累积印刷次数,直到检测到结束字符。

To prevent it from getting confused with the user typing, the keypresses should be relatively close (in time) to each other, you need to test it out and see what a good number of ms between keypresses is. Fast typers can type as fast as 50ms in between key presses.

为了防止它与用户输入混淆,按键应该彼此相对接近(在时间上),您需要对其进行测试,看看按键之间的毫秒数是多少。快速打字者可以在两次按键之间以最快 50 毫秒的速度打字。