扫码枪输入事件

137 阅读1分钟

起因公司需要做一个扫码功能

扫码功能本质也就是键盘输入事件 所以记录一下

代码

html 部分

<body>
    扫码枪输入: <input id="birthday" name="birthday" style="outline:none; width: 400px; height: 30px; font-size: 30px;" />
</body>

css 部分

    let code = ''
    let lastTime, nextTime
    let lastCode, nextCode
    let that = this
    window.document.onkeypress = function (e) {
        if (window.event) { // IE
            nextCode = e.keyCode
        } else if (e.which) { // Netscape/Firefox/Opera
            nextCode = e.which
        }
        if (e.which === 13) {
            if (code.length < 3) return // 手动输入的时间不会让code的长度大于2,所以这里只会对扫码枪有

           //此时为最终结果 可以把结果赋值给某个地方
            console.log(code)
            console.log('扫码结束')
            code = ''
            lastCode = ''
            lastTime = ''
            return
        }
        nextTime = new Date().getTime()
        //使用时间戳来记录
        if (!lastTime && !lastCode) {
            console.log('扫码开始。。。')
            code += e.key
        }
        if (lastCode && lastTime && nextTime - lastTime > 500) { // 当扫码前有keypress事件时,防止首字缺失
            console.log('防止首字缺失。。。')
            code = e.key
        } else if (lastCode && lastTime) {
            console.log('扫码中。。。')
            code += e.key
        }
        lastCode = nextCode
        lastTime = nextTime
    }