扫码枪是一种类似键盘的输入设备,扫码完成后会以极快的速度输入扫描到的字符,一般在末尾会带一个换行符。原理是检测 keydown 事件两次输入的间隔如果小于一个值的话就当成扫码枪输入。
barpreScanner.js
function BarpreScannerDetect(callback) { this.lastTime = null this.nextTime = null this.pre = '' this.detect = (e) => { const keypre = e.keyCode || e.which || e.charCode this.nextTime = new Date() // 回车键13 if (keypre === 13) { if (this.lastTime && this.nextTime - this.lastTime < 30) { // 扫码枪 // console.log(this.pre) callback(this.pre) } else { // 键盘 } this.pre = '' this.lastTime = null e.preventDefault() } else { // 忽略一些没用的字符以及中文输入法bug字符 if (keypre !== 16 && keypre !== 229) { if (!this.lastTime) { this.pre = String.fromCharCode(keypre) } else { if (this.nextTime - this.lastTime < 30) { // console.log(keypre, String.fromCharCode(keypre)) this.pre += String.fromCharCode(keypre) } else { this.pre = '' } } } this.lastTime = this.nextTime } }}BarpreScannerDetect.prototype.startDetect = function() { // console.log('startDetect') document.addEventListener('keydown', this.detect)}BarpreScannerDetect.prototype.stopDetect = function() { // console.log('stopDetect') document.removeEventListener('keydown', this.detect)}export default BarpreScannerDetect


