js获取USB扫码枪数据
程序员文章站
2022-06-14 19:38:35
...
前言
- 找了很多相关的教程不太好用,汲取各家之长总结精简了一下
原理
- 扫码枪扫描到的条形码每一位会触发一次onkeydown事件
比如扫描条码位‘1234567890’的条形码,会连续执行10次onkeydown事件 - 条码扫描到最后一位,会直接触发Enter
代码
需要引入jQuery,我这里用的是vue框架,使用可按需修改方法that.data部分
window.onload = function(e) {
document.onkeydown = (e)=> {
let nextCode,nextTime = '';
let lastTime = that.lastTime;
let code = that.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<=57) || (nextCode>=96&&nextCode<=105)){
let codes = {'48':48,'49':49,'50':50,'51':51,'52':52,'53':53,'54':54,'55':55,'56':56,'57':57,
'96':48,'97':49,'98':50,'99':51,'100':52,'101':53,'102':54,'103':55,'104':56,'105':57
};
nextCode = codes[nextCode];
nextTime = new Date().getTime();
}
// 第二次输入延迟两秒,删除之前的数据重新计算
if(nextTime && lastTime && nextTime-lastTime>2000){
code = String.fromCharCode(nextCode);
}else{
code += String.fromCharCode(nextCode)
}
// 保存数据
that.nextCode = nextCode;
that.lastTime = nextTime;
that.code = code;
// 键入Enter
if(e.which == 13) {
// 判断 code 长度(这里就获取到条码值了,以下业务*发挥)
code = $.trim(code)
if (code.length == 13) {
that.$message('A类条码:' + code);
} else if (code.length == 23) {
that.$message('B类条码:' + code);
} else if (code.length == 0) {
that.$message('请输入条码');
} else{
that.$message('条码不合法:' + code);
}
//键入回车务必清空code值
that.code = ''
return false;
}
}
}
上一篇: 安卓使用外接扫码枪扫描一维码之后EditText失去焦点的问题
下一篇: 大文件排序求频率TOP问题