js如何获取扫码枪输入数据-创新互联

这篇文章主要讲解了js如何获取扫码枪输入数据,内容清晰明了,对此有兴趣的小伙伴可以学习一下,相信大家阅读完之后会有帮助。

成都创新互联主营闽清网站建设的网络公司,主营网站建设方案,成都APP应用开发,闽清h5小程序定制开发搭建,闽清网站营销推广欢迎闽清等地区企业咨询

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 < 3) return; // 手动输入的时间不会让code的长度大于2,所以这里只会对扫码枪有

     console.log(code); // 获取到扫码枪输入的内容,做别的操作

     code = '';
     lastCode = '';
     lastTime = '';
     return;
    }
    nextTime = new Date().getTime();
    if (!lastTime && !lastCode) {
     code += e.key;
    }

    if (lastCode && lastTime && nextTime - lastTime > 30) { // 当扫码前有keypress事件时,防止首字缺失
     code = e.key;
    } else if (lastCode && lastTime) {
     code += e.key;
    }
    lastCode = nextCode;
    lastTime = nextTime;
   }

网页题目:js如何获取扫码枪输入数据-创新互联
本文地址:http://myzitong.com/article/cdoood.html