[vue]利用自定义指令处理系统键盘遮挡input输入框

2021-07-24  本文已影响0人  孙二柯
场景

当页面的input在页面的位置比较靠下时,获取焦点会弹出系统键盘。在ios系统中键盘会把页面顶起来,让输入框在键盘上吗。但是一些安卓系统,键盘会盖住页面的输入框,这时候就需要H5做一些处理。

处理

1.利用Element.scrollIntoView()或者Element.scrollIntoViewIfNeeded()scrollIntoView()方法会滚动元素的父容器,使被调用scrollIntoView()的元素对用户可见

element.scrollIntoView(); // 等同于element.scrollIntoView(true)
element.scrollIntoView(alignToTop); // Boolean型参数
element.scrollIntoView(scrollIntoViewOptions); // Object型参数

2.在vue中我们设置一个自定义指令

const inputIntoViewDirective = {
  inserted: function (el, binding, vnode) {
    // console.log('inserted', el)
    // scrollIntoView when element focus
    el.onfocus = () => {
      setTimeout(() => {
        el.scrollIntoView() //  https://developer.mozilla.org/zh-CN/docs/Web/API/Element/scrollIntoView
        // console.log('scrollIntoView')
      }, 400)
    }
  },
  unbind: function (el, binding, vnode) {
    el.onfocus = null
    // console.log('touchDirective--unbind')
  }

}

export default inputIntoViewDirective

3.在main.js中注册

// 引入自定义touch指令
import touchDirective from '@/plugins/touchDirective'
Vue.directive('intoView', inputIntoViewDirective)

4.在需要的地方添加指令v-intoView

<input
    type="text"
    v-model="phone"
    v-intoView
    placeholder="留下您的手机号码或邮箱,方便我们联系您"
/>
其他

如果没有效果的话,有可能是安卓弹出键盘的时候没有改变webview的高度,相当于键盘是在webview上层,遮挡住了页面。这个时候要原生的同事帮忙处理下
实现一个loading加载中的自定义指令

上一篇下一篇

猜你喜欢

热点阅读