背景

大量的页面需要进入时获得焦点,还有安卓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>
Logo

前往低代码交流专区

更多推荐