没有输入焦点时,Javascript捕获输入 [英] Javascript catch input when no input has focus

查看:95
本文介绍了没有输入焦点时,Javascript捕获输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有条形码扫描仪.

有时用户希望通过条形码搜索项目.

Sometimes user wants to search items by bar code.

但是他很懒惰,根本不想使用鼠标来单击输入.

But he is lazy enough and doens't want to use mouse at all to click on input.

扫描仪通常可以非常快速地输入8到13个符号,没有人类可以这么快地输入.

Scanner usually inputs from 8 to 13 symbols very fast, no human types so fast.

(1)检测到极高的输入并且如果页面上没有输入元素具有焦点(2),然后选择具有特定类别的输入,并用扫描仪中的内容填充并开始搜索,将是一个完美的解决方案.

It would be perfect solution to (1)detect extremely input and if no input element on the page has focus (2) then to select the input with certain class , fill it with content from scanner and start searching.

第二阶段没有问题.我不知道如何从第一阶段开始.

Second stage is non-issue. I 've no idea how to start with first stage.

有图书馆吗?

不是一个完美的解决方案,是对条形码阅读器进行编程,以某种组合键开始每次输入,然后监听此键并将焦点放在必要的输入上.但这需要其他人的额外工作.

Not perfect solution would be to program bar code reader to begin every entering with some key combination and listen for this key and set focus on necessary input. But this would require extra work of other guys.

可以找到完美的解决方案吗?

Is perfect solution reachable?

推荐答案

您可以通过在input中填写该键并赋予其焦点来对document上的keypress做出响应,如果按键的目标不是不是input:

You could respond to keypress on document by filling in that key in the input and giving it focus, if the target of the keypress isn't an input:

document.addEventListener("keypress", function(e) {
  if (e.target.tagName !== "INPUT") {
    var input = document.querySelector(".my-input");
    input.focus();
    input.value = e.key;
    e.preventDefault();
  }
});

<input type="text" class="my-input">

我很感兴趣地发现,如果我不阻止默认设置,则将焦点设置为Chrome可以在input(而不是Firefox)中键入字符.因此,preventDefault阻止Chrome执行此操作.

I was intrigued to find that if I didn't prevent the default, setting the focus made Chrome type the character in the input (but not Firefox). Hence the preventDefault to keep Chrome from doing that.

如果需要支持过时的浏览器,则可能需要使用keyCode和/或which进行一些操作,而不是使用

If you need to support obsolete browsers, you may need to do some playing around with keyCode and/or which rather than using key. MDN claims key support in any modern Chrome or Firefox and IE9+ (doesn't say for Edge).

这篇关于没有输入焦点时,Javascript捕获输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆