vue指令:v-focus实现el-input获得焦点,input获得焦点时不弹起键盘

背景

大量的页面需要进入时获得焦点,还有安卓pda扫描设备,需要获得焦点时,不触发键盘弹起。

源码

使用vue指令实现。你要不是用的vue, 也可以提取出来,@focus配合函数 实现。

// 添加全局v-focus指令
Vue.directive("focus", {
  inserted: function(el, { modifiers: { noKeyboard } }) {
    try {
      const tagName = el.tagName;
      if (tagName !== "INPUT") {
        let child = el.children[0];
        if (child && child.tagName === "INPUT") {
          el = child;
        }
      }
      // 可以重新获得焦点又不弹起软键盘;xxx是el-input的ref
      // this.$refs[xxx].$refs.input.noKeyboardFocus(); 
      el.noKeyboardFocus = function() {
        Vue.nextTick(() => {
          this.focus();
          this.setAttribute("readonly", "readonly");
          var timer = null;
          timer = setTimeout(() => {
            this.removeAttribute("readonly");
            clearTimeout(timer);
          }, 100);
        });
      };
      el.focus();
      // v-focus.noKeyboard 不弹起软键盘
      if (noKeyboard) {
        el.setAttribute("readonly", "readonly");
        var timer = null;
        timer = setTimeout(() => {
          el.removeAttribute("readonly");
          clearTimeout(timer);
        }, 100);
      }
    } catch (error) {
      throw new Error(error);
    }
  }
});

用法

使用noKeyboard修饰符: v-focus.noKeyboard,在初始化时就会获得焦点。

函数式:
this. r e f s [ x x x ] . refs[xxx]. refs[xxx].refs.input.noKeyboardFocus();

          <el-input
            v-focus.noKeyboard
            @keydown.native.enter="search()"
            v-model="searchParams.cellCode"
            placeholder="扫描"
          ></el-input>
  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 7
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值