<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body id="main">
<script>
window.onload = function(e){
let code = ;
let lastTime, nextTime;
let lastCode, nextCode;
window.document.onkeypress = function(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); // 获取到扫码枪输入的内容,做别的操作
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;
}
}
</script>
</body>
</html>