最近开发的一个项目中有一个获取验证码功能,在测试时遇到了问题。
H5页面在iOS系统微信浏览器中,input focus 聚焦时页面会被上推,导致页面整体上移。blur 失焦后不能恢复,再次点击 input 时没反应,不能聚焦,无法输入内容,这时候需要滑动一下页面才能恢复正常。
最后发现是因为 iOS 中 input 聚焦时会导致页面上移,失焦后页面不能恢复,但是 input 会恢复之前的位置(或者说下移)。这时再点击 input 是没反应的,就好比 input 身体虽然下来了,但是魂儿还在上面,也可以理解为 input 发生了位移/偏移。
要解决这个问题,需要在 input 失焦时调整页面的位置,使其恢复正常的位置。
比较简单的思路, input 失焦时,页面滚动到顶部(以 jQuery 为例):
$('input').on('blur',function(){
window.scroll(0,0);
});
javaScript 实现:
document.getElementById('#input').addEventListener('blur', function () {
window.scrollTo(0, 0) //页面滚动到顶部
},
false
)
我的项目是 Vue 写的, Vue 中有一个 @blur
属性,可以直接封装一个方法,直接在失焦时调用:
<!-- HTML code -->
<input @blur="inputBlur" placeholder="请输入验证码">
/* js code */
inputBlur(){
let u = navigator.userAgent,
isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
if(isIOS){ //判断是 iOS
setTimeout(() => {
const scrollHeight = document.documentElement.scrollTop || document.body.scrollTop || 0
window.scrollTo(0, Math.max(scrollHeight - 1, 0)) // 归位
}, 20)
}
}
监听键盘弹出关闭:可以全局引入
var u = navigator.userAgent,
flag,
toScroll,
isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
if (isIOS) {
document.body.addEventListener('focusin', () => { //软键盘弹起事件
flag = true;
clearTimeout(toScroll);
})
document.body.addEventListener('focusout', () => { //软键盘关闭事件
flag = false;
if (!flag) {
toScroll = setTimeout(function () {
window.scrollTo({ top: 0, left: 0, behavior: "smooth" })//重点 =======当键盘收起的时候让页面回到原始位置(这里的top可以根据你们个人的需求改变,并不一定要回到页面顶部)
}, 20);
} else {
return
}
})
} else {
return
}
声明:本文由w3h5原创,转载请注明出处:《iOS微信浏览器input聚焦导致页面上移,不能恢复的解决方法》 https://cloud.tencent.com/developer/article/1594907
本文已加入 腾讯云自媒体分享计划 (点击加入)
(adsbygoogle = window.adsbygoogle || []).push({});