iOS微信瀏覽器input聚焦導致頁面上移,不能恢復的解決方法
- 2020 年 3 月 6 日
- 筆記
最近開發的一個項目中有一個獲取驗證碼功能,在測試時遇到了問題。

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://www.w3h5.com/post/483.html
本文已加入 騰訊雲自媒體分享計劃 (點擊加入)
(adsbygoogle = window.adsbygoogle || []).push({});