Vue 自定义指令 解决IOS webview input 获取焦点被键盘遮挡
创建自定义指令 在使用input的地方添加自定义指令,记录一下还有优化空间。
<div id="content">
<input v-cover type="text" />
</div>
/**
* 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)
}
import inputCover from '@/directive/cover'
Vue.use(inputCover)