---- js 獲取掃碼槍
不需要記錄 lastCode 啊,只需要在時間超出范圍的時候重置 lastTime 和 code 就行了。如果
碼槍會輸入回車,那就在 keyCode === 13 的時候使用 code 就行。這時候如果 code 的值多於
1個字符就一定是碼槍輸入的,沒有值就是手工輸入的……如果需要記錄手工輸入的值,可以使
用另一個變量比如 manualCode 來記錄,在回車的時候如果 code 無值就從 manualCode 中截取
后面若干字符出來,再適時把 manualCode 清空就好。
示意(只有判斷時間和拼接 code):
let start = new Date();
let code = "";
$("#test").on("keydown", (e) => {
now = new Date();
if (now - start > 50) {
start = now;
code = String.fromCharCode(e.keyCode);
} else {
code += String.fromCharCode(e.keyCode);
console.log(code);
}
});
