js获取扫码枪输入

场景:
扫码枪扫码,获取信息,js代码如何获取扫描信息呢?

原理:
扫码枪输入会触发键盘输入事件。
扫码枪输入的时间间隔一般在8毫秒,偶尔会有16毫秒,而键盘输入一般都在80毫秒以上。

        var keycode = "";
        var lastTime=null;
        var nextTime=null;
        var lastCode=null;
        var nextCode=null;

        document.onkeydown=function(e){
            //兼容性处理
            if(window.event){
                nextCode = e.keyCode
            } else if(e.which){
                nextCode = e.which
            }
            
            //获取当前时间
            nextTime = new Date().getTime();
              
            if(nextCode==13 && keycode!= "" && nextTime - lastTime <= 30){//回车字符
                console.log(keycode);
                keycode = "";
                lastCode = null;
                lastTime = null;
            }else{//此处可以增加限制nextCode的种类例如数字
                if(lastCode == null && lastTime == null){//初始字母
                    keycode = String.fromCharCode(nextCode);
                }else if(lastCode != null && lastTime != null && nextTime - lastTime <= 30){
                    keycode += String.fromCharCode(nextCode);
                }else{//手动输入
                    keycode = "";
                    lastCode = null;
                    lastTime = null;
                }
                lastCode = nextCode;
                lastTime = nextTime;
            }
        }

你可能感兴趣的:(js获取扫码枪输入)