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.userAgentconst isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)const inputDirective = {inserted: function (el: HTMLElement) {el.onfocus = () => {if (isiOS) {// 计算偏移量let windowHeight = window.screen.heightlet top = el.getBoundingClientRect().toplet 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)