解决ios键盘收起后页面显示异常问题
问题出现背景:部分ios机型,收起键盘后,滚动位置不能恢复
解决方法:记录滚动位置,绑定事件手动恢复。
代码实现
1.在合适时机绑定上事件
// 事件绑定
if(this.iSiPhoneXR()){
this.scrollTop =(document['scrollingElement']&&document['scrollingElement'].scrollTop) ||document.body.scrollTop
document.body.style.top = -this.scrollTop + 'px'
const oldScrollTop = this.getScrollTop() || 0
sessionStorage.setItem('addKeyboardListener',JSON.stringify(oldScrollTop))
document.body.addEventListener('focusin',this.setScrollTopInFn)
document.body.addEventListener('focusout', this.setScrollTopOutFn)
}
- 工具函数
// 判断ios特殊机型
iSiPhoneXR(){
return /iphone/gi.test(window.navigator.userAgent) &&
window.devicePixelRatio &&
window.devicePixelRatio === 2 &&
window.screen.width === 414 &&
window.screen.height === 896
}
// 获取当前滚动位置
getScrollTop () {
let scrollTop = 0
if (document.documentElement && document.documentElement.scrollTop) {
scrollTop = document.documentElement.scrollTop
} else if (document.body) {
scrollTop = document.body.scrollTop
}
return scrollTop
}
- 事件处理函数
// 记录打开输入框时滚动位置
setScrollTopInFn(){
try {
const oldScrollTop =JSON.parse(sessionStorage.getItem('addKeyboardListener'))
document.body.scrollTop = -oldScrollTop
document.documentElement.scrollTop = -oldScrollTop
} catch (error) {
console.log(error)
}
}
// 收起输入框时恢复滚动位置
setScrollTopOutFn(){
try {
const oldScrollTop =JSON.parse(sessionStorage.getItem('addKeyboardListener'))
document.body.scrollTop = oldScrollTop
document.documentElement.scrollTop = oldScrollTop
} catch (error) {
console.log(error)
}
}
- 在合适的时机进行事件解绑
if(this.iSiPhoneXR()){
document.body.removeEventListener('focusin',this.setScrollTopInFn)
document.body.removeEventListener('focusout', this.setScrollTopOutFn)
}