問題:
在IOS上點擊input框軟鍵盤彈出,頁面上移。點擊軟鍵盤上完成按鈕軟鍵盤關閉,但頁面並沒有下移。
解決:
監聽軟鍵盤彈起、關閉事件。在鍵盤關閉時對頁面重新定位
// 兼容部分ios手機input失焦後頁面上移問題
(function() {
let myFunction
let isWXAndIos = isWeiXinAndIos()
if (isWXAndIos) { // 既是微信瀏覽器 又是ios============(因爲查到只有在微信環境下,ios手機上纔會出現input失去焦點的時候頁面被頂起)
document.body.addEventListener('focusin', () => { // 軟鍵盤彈起事件
clearTimeout(myFunction)
})
document.body.addEventListener('focusout', () => { // 軟鍵盤關閉事件
clearTimeout(myFunction)
myFunction = setTimeout(function() {
window.scrollTo({top: 0, left: 0, behavior: 'smooth'})// 重點 =======當鍵盤收起的時候讓頁面回到原始位置
}, 200)
})
}
})()
function isWeiXinAndIos() {
// window.navigator.userAgent屬性包含了瀏覽器類型、版本、操作系統類型、瀏覽器引擎類型等信息,這個屬性可以用來判斷瀏覽器類型
let ua = '' + window.navigator.userAgent.toLowerCase()
// 通過正則表達式匹配ua中是否含有MicroMessenger字符串且是IOS系統
let isWeixin = /MicroMessenger/i.test(ua) // 是在微信瀏覽器
let isIos = /\(i[^;]+;( U;)? CPU.+Mac OS X/i.test(ua) // 是IOS系統
return isWeixin && isIos
}