Vue 自定义指令 解决IOS webview input 获取焦点被键盘遮挡

Vue 自定义指令 解决IOS webview input 获取焦点被键盘遮挡

创建自定义指令 在使用input的地方添加自定义指令,记录一下还有优化空间。
  • vue 文件
<div id="content">
    <input v-cover type="text" />
</div>
  • cover.js 文件
/**
 * v-cover
 * input获取焦点键盘遮挡问题
 */
import type {VueConstructor} from 'vue'

const u = navigator.userAgent
  
const isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)

const inputDirective = {
  
  inserted: function (el: HTMLElement) {
    el.onfocus = () => {
      if (isiOS) {
        // 计算偏移量
        let windowHeight =  window.screen.height
        let top = el.getBoundingClientRect().top
        let deviation =  450 - (windowHeight - top - el.clientHeight)
        setTimeout(() => {
          (document.getElementById('content') as any).style=`transform:translateY(${deviation > 0 ? -deviation : 0}px);transition:0.1s`
        }, 400)
      }
    }
    el.onblur = () => {
      if (isiOS) {
        setTimeout(() => {
          (document.getElementById('content') as any).style=`transform:translateY(0);transition:0.1s`
        }, 400)
      }
    }
  },
  unbind: function (el: HTMLElement) {
    el.onfocus = null
  }

}


export default (app: VueConstructor) => {
  //自定义指令
  app.directive('cover', inputDirective)
}

  • app.ts
import inputCover from '@/directive/cover'

Vue.use(inputCover)
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值