跳转页面input输入框自动聚焦弹起手机软键盘,兼容安卓和ios

需求是这样:点击某个页面或某个页面的模块,跳转到带搜索的子页面,并且自动弹出手机软键盘。

长话短说,代码:

// 封装一个自动聚焦的函数,兼容ios和安卓
const autofocusFn = () => {
  const doc = document
  const input = doc.querySelector('#hide-focus-input')
  let dom = null
  // 1.检查文档有没有一个id为hide-focus-input的input标签
  // 2.如果有,dom等于这个input标签
  // 3.如果没有,则创建一个id为hide-focus-input的input标签,并添加样式(第一次执行时走这步)
  // 4.调通input的原生focus方法来聚焦
  if (input) {
    dom = input
  } else {
    dom = doc.createElement('input')
    dom.setAttribute('id', 'hide-focus-input')
    dom.style = 'position: absolute; z-index: -9999; width: 0; height: 0; left:-9999px; top:0 '
    doc.body.appendChild(dom)
  }
  dom.focus()
}
//如果是封装在一个js文件,则暴露出去,在用的地方用import引入
export { autofocusFn }

 

函数已经封装好了,接下来就是调用:

1.先引入autofocusFn 函数

2.跳转前调用(比如在VUE里面使用)

<template>
  <div @click="searchClick">点击搜索</div>
</template>
<script>
import { autofocusFn } from '你放函数的文件路径'
export default {
  methods: {
    searchClick() {
      autofocusFn()
      this.$router.push('真正带搜索input的页面')
    },
  },
}
</script>

 

最后一步,在需要弹出键盘的页面手动调用input的聚焦方法

比如普通input:

<template>
  <div>
    <input v-model="searchVal" autofocus ref="searchRef" />
  </div>
</template>

<script>
export default {
  data() {
    return {
      searchVal: '',
    }
  },
  mounted() {
    this.$refs.searchRef.focus()
  },
}
</script>

<style></style>

 

比如在vant:
<template>
  <div>
    <van-search v-model="searchVal" autofocus ref="searchRef" />
  </div>
</template>

<script>
export default {
  data() {
    return {
      searchVal: '',
    }
  },
  mounted() {
    this.$refs.searchRef.focus()
  },
}
</script>

<style></style>

 

 

posted @ 2023-05-11 13:20  william_new  阅读(1529)  评论(0编辑  收藏  举报