监听读卡器刷卡事件

发布时间 2023-04-12 15:18:48作者: Bing-haha

web浏览器使用ic卡或磁卡读卡器自动弹出页面,参考:web浏览器使用ic卡或磁卡读卡器自动弹出页面 - HelpYourself! - 博客园 (cnblogs.com)

在页面内单独设置一个input框

<el-input ref="myInput" v-model="myInputModel" id="myInput" style="position:fixed;top:-100px;"></el-input>

页面渲染之后,监听:

mounted() {
    this.inputTimer = setInterval(() => {
      // 如果当前页面没有聚焦的input,则让隐藏的input聚焦
      if (!$('input:focus').length) {
        this.$refs.myInput.focus();
      }
    }, 500)

    this.$nextTick(() => {
      this.$refs.myInput.focus();

      document.getElementById('myInput').onblur = () => {
        console.log("监听失焦事件-----");
      }


      document.getElementById('myInput').addEventListener('focus', () => {
        console.log("监听聚焦事件-----")
      });
    });
    let _this = this;
    window.addEventListener('keydown', e => listenReader(e, _this))

  },

监听读卡器刷卡的操作:

listenReader(e) {
      let _this = this;
      document.onkeypress = (e) => zx(e);
      _this.readerSwip = false;
        function zx(e) {
          _this.nextCode = e.keyCode;// 当前的键码
          _this.nextTime = new Date().getTime();// 当前的毫秒数
          // 大写字母键值范围  A~Z(a~z): 65~90
          // 有时会出现 a~z: 97~122
          // 数字键值范围  0~9: 48~57

          // 数字键盘上的数字键范围 0~9: 96~105
          // if (_this.nextCode >= 48 && _this.nextCode <= 57) {// 只关注数字键
          let res = Number(_this.nextTime) - Number(_this.lastTime);
            if (_this.lastCode != null && _this.lastTime != null && res <= 20) {// 相差30以内说明是机器刷卡
              // console.log('机器刷卡--aa--', res)
              _this.handleReaderAction(e);
            } else {// 手动在输入
              // console.log("手动输入----aa--", res)
            }
              // 当前的键盘码和时间作为下一次的上一次
              _this.lastCode = _this.nextCode;
              _this.lastTime = _this.nextTime;
          
        }
    },
handleReaderAction函数:
this.readerSwip = true ---- 是读卡器刷卡,不是手动输入;
readerValue :读卡器读出来的值
handleReaderAction(e) {
      if(this.time !== null){
        clearTimeout(this.time);
      }
      this.time = setTimeout(() => {
        let value = e.target?.value || '';
        this.readerValue = e?.target?.value || '';
        this.readerSwip = true;
        // 清空上次读卡的值
        e.target.value = ''

        // 处理刷卡逻辑
        this.handleReadCard();
      },50)
    },
handleReadCard: 处理刷卡逻辑,与自己业务相关代码