一起看看js获取扫码枪输入数据的方法

一起看看js获取扫码枪输入数据的方法

1、扫码枪相当于键盘输入设备,输入一连串数字后加一个enter键。但在实际开发中需要区分是扫描枪输入还是键盘用户输入,区别在于扫码枪输入很快。

 let code = '';   let lastTime, nextTime;   let lastCode, nextCode;   window.document.onkeypress = (e) => {    if (window.event) { // IE     nextCode = e.keyCode;    } else if (e.which) { // Netscape/Firefox/Opera     nextCode = e.which;    }    if (nextCode === 13) {     if (code.length  30) { // 当扫码前有keypress事件时,防止首字缺失     code = e.key;    } else if (lastCode && lastTime) {     code += e.key;    }    lastCode = nextCode;    lastTime = nextTime;   }

登录后复制

PS:下面看下js获取USB扫码枪数据的代码

前言

找了很多相关的教程不太好用,汲取各家之长总结精简了一下

原理

扫码枪扫描到的条形码每一位会触发一次onkeydown事件比如扫描条码位‘1234567890’的条形码,会连续执行10次onkeydown事件条码扫描到最后一位,会直接触发Enter

需要引入jQuery,我这里用的是vue

window.onload = (e)=> {  document.onkeydown = (e)=> {  let nextCode,nextTime = '';  let lastTime = this.lastTime;  let code = this.code;    if (window.event) {// IE      nextCode = e.keyCode    } else if (e.which) {// Netscape/Firefox/Opera      nextCode = e.which    }    nextTime = new Date().getTime();    //字母上方 数字键0-9 对应键码值 48-57; 数字键盘 数字键0-9 对应键码值 96-105    if((nextCode>=48&&nextCode=96&&nextCode2000){code = String.fromCharCode(nextCode);    }else{    code += String.fromCharCode(nextCode)    }    // 保存数据    this.nextCode = nextCode;    this.lastTime = nextTime;    this.code = code;  // 键入Enter    if(e.which == 13) {      // 判断 code 长度(这里就获取到条码值了,以下业务自由发挥)      code = $.trim(code)      if (code.length == 13) {        this.$message('A类条码:' + code);      } else if (code.length == 23) {this.$message('B类条码:' + code);      } else if (code.length == 0) {this.$message('请输入条码');      } else{      this.$message('条码不合法:' + code);      }      //键入回车务必清空code值    this.code = ''    return false;    }  }}

登录后复制

相关学习推荐:javascript视频教程

以上就是一起看看js获取扫码枪输入数据的方法的详细内容,更多请关注【创想鸟】其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。

发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2726811.html

(0)
上一篇 2025年3月7日 23:38:16
下一篇 2025年2月23日 22:02:53

AD推荐 黄金广告位招租... 更多推荐

相关推荐

发表回复

登录后才能评论