業務需求要將數據生成二維碼,並用掃碼槍掃出數據上傳到服務端。
先上代碼吧,以後再完善注意點this
this.start = new Date().getTime() 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 } console.time() console.log('nextCode', nextCode) if (e.which === 13) { if (code.length < 3) return // 手動輸入的時間不會讓code的長度大於2,因此這裏只會對掃碼槍有 console.log(code) console.log('掃碼結束') console.timeEnd() that.parseQRCode(code) // 獲取到掃碼槍輸入的內容,作別的操做 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 }