当前位置:主页 > 网页前端 > JavaScript代码 >

使用JavaScript获取扫码枪扫描得到的条形码的思路代码详解

时间:2020-12-27 16:17:54 | 栏目:JavaScript代码 | 点击:

下面通过实例代码给大家介绍js扫码枪扫描条形码的实现方法,具体代码如下所示:

 var keycode = "";
  var lastTime=null,nextTime;
  var lastCode=null,nextCode;
	document.οnkeydοwn=function(e){
		if(window.event){
			// IE
			nextCode = e.keyCode
		} else if(e.which){
			// Netscape/Firefox/Opera
			nextCode = e.which
		}
		
		//+键,增加新数据行
		if(nextCode==107 || nextCode==187){
			addNewGoodLine();
		} 
		//-键,删除最后一条数据行
		else if(nextCode==109 || nextCode==189){
			$(".new_products:last").remove();
		}
		//字母上方 数字键0-9 对应键码值 48-57
		//数字键盘 数字键0-9 对应键码值 96-105
		else if((nextCode>=48&&nextCode<=57) || (nextCode>=96&&nextCode<=105)){
			//数字键盘的键码值对应的字符有问题,所以手动调整键码值
			var 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();
		  if(lastCode == null && lastTime == null) {
		  	keycode = String.fromCharCode(nextCode);
		  } else if(lastCode != null && lastTime != null && nextTime - lastTime <= 30) {
		  	keycode += String.fromCharCode(nextCode);
		  } else{
				keycode = "";
			  lastCode = null;
			  lastTime = null;
			}
		  lastCode = nextCode;
		  lastTime = nextTime;
		}
		//13 为按键Enter
		else if(nextCode==13 && keycode!= ""){
			var code = $(".new_products:last .code").val();
			if(code != ""){
				//最后一行已录入数据,重新生成新行
				addNewGoodLine();
			}
			$(".new_products:last .code").val(keycode).blur();
			keycode = "";
		  lastCode = null;
		  lastTime = null;
		}
	}
	
	function addNewGoodLine(){
		//生成新数据行
		var html = '<tr class="new_products">';
			html += '	<td></td>';
			html += '	<td>';
			html += '		<input type="text" class="code" οnblur="getProductDetail()" />';
			html += '	</td>';
			html += '</tr>';
	}
	
	function getProductDetail(){
		//获取商品的详细信息,然后赋值
		
	}

思路:

1.注册onkeydown事件,捕获数字键的按下事件

2.计算按下数字键的时间间隔,若间隔小于30毫秒,则为扫码枪输入

3.捕获Enter案件的按下事件,判断捕获的扫码枪输入数值是否为空,不为空,对相应的文本框赋值,同时触发按找条形码查找商品的方法

总结

您可能感兴趣的文章:

相关文章