js 獲取掃碼槍輸入數(shù)據(jù)的方法
1、掃碼槍相當(dāng)于鍵盤輸入設(shè)備,輸入一連串?dāng)?shù)字后加一個(gè)enter鍵。但在實(shí)際開(kāi)發(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)了一下
原理
掃碼槍掃描到的條形碼每一位會(huì)觸發(fā)一次onkeydown事件 比如掃描條碼位‘1234567890’的條形碼,會(huì)連續(xù)執(zhí)行10次onkeydown事件 條碼掃描到最后一位,會(huì)直接觸發(fā)Enter需要引入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; } }}
總結(jié)
到此這篇關(guān)于js 獲取掃碼槍輸入數(shù)據(jù)的文章就介紹到這了,更多相關(guān)js 獲取掃碼槍輸入數(shù)據(jù)內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. asp批量添加修改刪除操作示例代碼2. 低版本IE正常運(yùn)行HTML5+CSS3網(wǎng)站的3種解決方案3. PHP循環(huán)與分支知識(shí)點(diǎn)梳理4. css代碼優(yōu)化的12個(gè)技巧5. ASP刪除img標(biāo)簽的style屬性只保留src的正則函數(shù)6. ASP實(shí)現(xiàn)加法驗(yàn)證碼7. jsp+servlet實(shí)現(xiàn)猜數(shù)字游戲8. JSP+Servlet實(shí)現(xiàn)文件上傳到服務(wù)器功能9. 讀大數(shù)據(jù)量的XML文件的讀取問(wèn)題10. 解析原生JS getComputedStyle
