解决ios键盘收起后页面显示异常问题

解决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)
}
  1. 工具函数
// 判断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
}
  1. 事件处理函数
// 记录打开输入框时滚动位置
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)
	}	
}
  1. 在合适的时机进行事件解绑
if(this.iSiPhoneXR()){
	document.body.removeEventListener('focusin',this.setScrollTopInFn)
	document.body.removeEventListener('focusout', this.setScrollTopOutFn)
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值