Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

外接设备扫码枪问题 #21

Open
Ray-56 opened this issue Jul 3, 2020 · 0 comments
Open

外接设备扫码枪问题 #21

Ray-56 opened this issue Jul 3, 2020 · 0 comments
Labels
JavaScript JavaScript 语言相关

Comments

@Ray-56
Copy link
Owner

Ray-56 commented Jul 3, 2020

外接设备扫码枪问题

起因

项目中需要加入一个扫描条形码添加货品的功能. 咦~功能是个好功能, 可是扫码枪如何扫码? 小朋友是否有很多问号

扫码枪

查阅资料可知, 其实扫码枪扫描二维码简直不要太简单.
扫码枪也是属于物理硬件与键盘无二. 不同是在于扫码枪的功能单一, 只能做输入以及回车等.
对于前端来说, 判断依据:

  • 已获取焦点的input或者其它输入框
  • 判断输入时间间隔来判断究竟是扫码枪还是键盘. 经过实测, 扫码枪输入的时间间隔一般在8毫秒, 有时也会是16毫秒, 而键盘输入一般都在80毫秒以上, 因此可以依据输入间隔 <= 30毫秒时.
  • 监听enter按下事件.
    以上3点同时满足时即为扫码枪扫描

实现

在vue中 鼠标点击获取焦点后扫描:

<template>
    <input type="text"
        v-model="value"
        @keydown.13="onEnter">
</template>

<script>
    export default {
        data() {
            return {
                value: ''
            }
        },
        methods: {
            onEnter() {
                console.log(this.value); // 扫码枪 输入的值
            },
        }
    }
</script>

jQuery中:

<!DOCTYPE html>  
<html lang="en">  
<head>  
    <meta charset="UTF-8">  
    <title>键盘按键监听测试</title>  
</head>  
<body>  
    <input name="name" placeholder="name" />  
    <input id='birthday' name="birthday" placeholder="birthday" />  
</body>  
</html>  
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>  
<script type="text/javascript">  
    $("#birthday").focus();  
    function keyDown(e){  
        //IE内核浏览器  
        if (navigator.appName == 'Microsoft Internet Explorer'){  
            var keycode = event.keyCode;  
            var realkey = String.fromCharCode(event.keyCode);  
        } else { // 非IE内核浏览器  
            var keycode = e.which;  
            var realkey = String.fromCharCode(e.which);  
        }
        // console.log('按键码:' + keycode +  '字符: ' + realkey);  
  
        if (keycode === 13) {  
            console.log($("#birthday").val());  
        }
    };
    document.onkeydown = keyDown;
</script>

注意点

change事件: 是每输入一次都会返回.
条码如果为英文字母: 这个问题是在项目中遇到的, 在扫描英文字母的条码时会获取不到. 这是看看当前输入法是否为中文, 如果为中文则改为英文即可.

@Ray-56 Ray-56 added the JavaScript JavaScript 语言相关 label Jul 3, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
JavaScript JavaScript 语言相关
Projects
None yet
Development

No branches or pull requests

1 participant