有什么方法使js獲取掃碼槍輸入數(shù)據(jù)?很多新手對(duì)此不是很清楚,為了幫助大家解決這個(gè)難題,下面小編將為大家詳細(xì)講解,有這方面需求的人可以來學(xué)習(xí)下,希望你能有所收獲。
1、掃碼槍相當(dāng)于鍵盤輸入設(shè)備,輸入一連串?dāng)?shù)字后加一個(gè)enter鍵。但在實(shí)際開發(fā)中需要區(qū)分是掃描槍輸入還是鍵盤用戶輸入,區(qū)別在于掃碼槍輸入很快。
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; // 手動(dòng)輸入的時(shí)間不會(huì)讓code的長(zhǎng)度大于2,所以這里只會(huì)對(duì)掃碼槍有 console.log(code); // 獲取到掃碼槍輸入的內(nèi)容,做別的操作 code = ''; lastCode = ''; lastTime = ''; return; } nextTime = new Date().getTime(); if (!lastTime && !lastCode) { code += e.key; } if (lastCode && lastTime && nextTime - lastTime > 30) { // 當(dāng)掃碼前有keypress事件時(shí),防止首字缺失 code = e.key; } else if (lastCode && lastTime) { code += e.key; } lastCode = nextCode; lastTime = nextTime; }
PS:下面看下js獲取USB掃碼槍數(shù)據(jù)的代碼
前言
找了很多相關(guān)的教程不太好用,汲取各家之長(zhǎng)總結(jié)精簡(jiǎn)了一下
原理
需要引入jQuery,我這里用的是vue
window.onload = (e)=> { document.onkeydown = (e)=> { let nextCode,nextTime = ''; let lastTime = this.lastTime; let code = this.code; if (window.event) {// IE nextCode = e.keyCode } else if (e.which) {// Netscape/Firefox/Opera nextCode = e.which } nextTime = new Date().getTime(); //字母上方 數(shù)字鍵0-9 對(duì)應(yīng)鍵碼值 48-57; 數(shù)字鍵盤 數(shù)字鍵0-9 對(duì)應(yīng)鍵碼值 96-105 if((nextCode>=48&&nextCode<=57) || (nextCode>=96&&nextCode<=105)){ let codes = {'48':48,'49':49,'50':50,'51':51,'52':52,'53':53,'54':54,'55':55,'56':56,'57':57, '96':48,'97':49,'98':50,'99':51,'100':52,'101':53,'102':54,'103':55,'104':56,'105':57 }; nextCode = codes[nextCode]; nextTime = new Date().getTime(); } // 第二次輸入延遲兩秒,刪除之前的數(shù)據(jù)重新計(jì)算 if(nextTime && lastTime && nextTime-lastTime>2000){ code = String.fromCharCode(nextCode); }else{ code += String.fromCharCode(nextCode) } // 保存數(shù)據(jù) this.nextCode = nextCode; this.lastTime = nextTime; this.code = code; // 鍵入Enter if(e.which == 13) { // 判斷 code 長(zhǎng)度(這里就獲取到條碼值了,以下業(yè)務(wù)自由發(fā)揮) code = $.trim(code) if (code.length == 13) { this.$message('A類條碼:' + code); } else if (code.length == 23) { this.$message('B類條碼:' + code); } else if (code.length == 0) { this.$message('請(qǐng)輸入條碼'); } else{ this.$message('條碼不合法:' + code); } //鍵入回車務(wù)必清空code值 this.code = '' return false; } } }
看完上述內(nèi)容是否對(duì)您有幫助呢?如果還想對(duì)相關(guān)知識(shí)有進(jìn)一步的了解或閱讀更多相關(guān)文章,請(qǐng)關(guān)注億速云行業(yè)資訊頻道,感謝您對(duì)億速云的支持。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。