jQuery: How do I listen for general keyboard input?

后端 未结 2 1587
不知归路
不知归路 2020-12-16 00:15

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

相关标签:
2条回答
  • 2020-12-16 00:45

    Try this:

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

    See it in action on jsFiddle

    0 讨论(0)
  • 2020-12-16 00:52

    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.

    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.

    0 讨论(0)
提交回复
热议问题