网页使用扫码枪

首先,开宗明义:扫码枪就是一个输入工具,类似键盘,不过输入速度快,而且可以设置输入完成后自动触发回车。

参考文档:

  1. 了解键盘的3个事件:onkeydownonkeypressonkeyup

  2. 链接的示例程序中有一个String.fromCharCode方法,这个方法将 Unicode 编码转为一个字符,因为键盘事件的代码是Unicode编码

  3. keyCode,charCode,which的区别,参考博客1参考博客2,根据浏览器不同,键盘触发的事件不同,选取合适的代码,(烦人的兼容性~)

  4. “扫码枪本质是触发键盘事件。扫描过程就像是在键盘上敲击相应的键,keycode和键盘是一一对应的,只是输入速度(间隔时间)比物理键盘输入要快得多”,实例参考1实例参考2

参考上述,即可实现扫码枪功能,我用到的比较简单,实际代码附下:

$(function () {
//监听input回车事件,textbox('textbox')是因为我是用了EasyUI,需要加上这个以获取Jquery对象,原生input可删掉
$("#inputId").textbox('textbox').on("keyup", function (e) {
                if (e.keyCode == '13') {
                    //搜索函数
                }
            });
//方便人员操作,点击输入框即清空之前的数据
$("#inputId").textbox('textbox').on("click", function (e) {
                $('#inputId').textbox('clear');
            });
//初始化时聚焦,方便人员操作,进页面后不用手动点选输入框
$('#inputId').textbox('textbox').focus();
        })

补充知识:

  1. JQuery的on绑定事件,on可以用来绑定多个事件,绑定自定义事件(trigger),传递参数,向未来元素添加动作等。$(selector).on(event,childSelector,data,function)

  注意区分代码1和代码2的区别,代码2之后添加的<p>无动作~

<!DOCTYPE html>
<html>
<head>
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
  $("div").on("click","p",function(){
    $(this).slideToggle();
  });
  $("button").click(function(){
    $("<p>This is a new paragraph.</p>").insertAfter("button");
  });
});
</script>
</head>
<body>

<div style="background-color:yellow">
<p>This is a paragraph.</p>
<p>Click any p element to make it disappear. Including this one.</p>
<button>Insert a new p element after this button</button>
</div>

</body>
</html>
代码1
<!DOCTYPE html>
<html>
<head>
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
  $("p").on("click",function() {
      $(this).slideToggle();
  });
  $("button").click(function(){
    $("<p>This is a new paragraph.</p>").insertAfter("button");
  });
});
</script>
</head>
<body>

<div style="background-color:yellow">
<p>This is a paragraph.</p>
<p>Click any p element to make it disappear. Including this one.</p>
<button>Insert a new p element after this button</button>
</div>

</body>
</html>
代码2

  2.  JQuery的trigger方法触发事件$(selector).trigger(event,eventObj,param1,param2,...)

猜你喜欢

转载自www.cnblogs.com/lq67/p/11271066.html