您好,登錄后才能下訂單哦!
這篇文章主要講解了js如何獲取掃碼槍輸入數(shù)據(jù),內(nèi)容清晰明了,對此有興趣的小伙伴可以學(xué)習(xí)一下,相信大家閱讀完之后會有幫助。
1、掃碼槍相當于鍵盤輸入設(shè)備,輸入一連串數(shù)字后加一個enter鍵。但在實際開發(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; // 手動輸入的時間不會讓code的長度大于2,所以這里只會對掃碼槍有 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) { // 當掃碼前有keypress事件時,防止首字缺失 code = e.key; } else if (lastCode && lastTime) { code += e.key; } lastCode = nextCode; lastTime = nextTime; }
PS:下面看下js獲取USB掃碼槍數(shù)據(jù)的代碼
前言
找了很多相關(guān)的教程不太好用,汲取各家之長總結(jié)精簡了一下
原理
需要引入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 對應(yīng)鍵碼值 48-57; 數(shù)字鍵盤 數(shù)字鍵0-9 對應(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ù)重新計算 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 長度(這里就獲取到條碼值了,以下業(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('請輸入條碼'); } else{ this.$message('條碼不合法:' + code); } //鍵入回車務(wù)必清空code值 this.code = '' return false; } } }
看完上述內(nèi)容,是不是對js如何獲取掃碼槍輸入數(shù)據(jù)有進一步的了解,如果還想學(xué)習(xí)更多內(nèi)容,歡迎關(guān)注億速云行業(yè)資訊頻道。
免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。