h5 ios輸入框與鍵盤 相容性優化
起因
h5的輸入框引起鍵盤導致體驗不好,目前就算微信、知乎、百度等產品也沒有很好的技術方案實現,尤其底部固定位置的輸入框各種方案都用的前提下體驗也並沒有很好,這個問題也是老大難問題了。目前在準備一套與native協議 來解決這個問題,目前專案中的解決方案還是有值得借鑑的地方的,分享一下
業務場景
固定在h5頁面底部的輸入框
無論是使用
<input />
還是
<div contenteditable="true"> </div>
在聚焦事件觸發調起原生鍵盤時,在ios 部分機型(iphone 4s iphone 5等)上會使得鍵盤彈起後遮擋住輸入框,使得使用者體驗不好。
目前的解決方案是寫一個定時任務,在判定是ios開啟頁面時,執行以下函式
let timer = setInterval(()=>{ // container 知道整個容器的dom節點 container.scrollIntoView({ block: 'start', behavior: 'auto' }) },300); //300毫秒是經過多次試驗得到的數值,使用者體驗為佳
關於scrollIntoView
scrollIntoView這個API,官方的解釋是
The Element.scrollIntoView() method scrolls the element on which it's called into the visible area of the browser window.
語法
element.scrollIntoView(); // 等同於element.scrollIntoView(true) element.scrollIntoView(alignToTop); // Boolean型引數 element.scrollIntoView(scrollIntoViewOptions); // Object型引數
引數
引數 | 說明 | 型別 | 可選值 | 預設值 |
---|---|---|---|---|
alignToTop | -- | boolean | --- | false |
scrollIntoViewOptions | -- | object | -- | -- |
{ behavior: "auto"| "instant" | "smooth", block:"start" | "end", }
在can i use中查到的scrollIntoView的相容性(主流瀏覽器中不考慮ie)
- Firefox 36 以上相容
- chrome 61 以上相容
- safiri 5.1開始 不相容behavior中的smooth
後續問題
當然,這個解決方案智慧解決部分機型的問題,要真正解決這個問題還是要依靠native端。
在ios 和 安卓機型的問題
因為設定了這個定時任務,就會有一個後續的問題出現,也是在落地專案中有遇到過的,在此說明一下。
在上拉或下拉到頭時,會出現背景白色的現象,因為有了這個定時器,它就會不斷將檢視拉回,導致頁面抖動。
如果在app層做了webview禁止拖動的話就不會有這個問題,當然不能完全依賴app,在程式中我們也需要做此方面的相容優化。
<div class="container" @touchStart="touchStart($event)" @touchEnd="touchEnd($event)"> </div>
touchStart(e) { this.clearTimer(); }, touchEnd(e) { this.repairIosInput(); }, clearTimer() { if(this.timer) { clearInterval(this.timer); this.timer = null; }else{ return; } }, repairIosInput() { if(this.timer) { return; } this.timer = setInterval(()=>{ container.scrollIntoView({ block: 'start', behavior: 'auto' }) },300); }
在開始拉動頁面時清空定時器,停止拉動時開啟定時器,這樣就可以解決造成的抖動的問題了。
總結
做為一個老大難的問題,還會用更多的解決方案,請與我聯絡,一起討論,早日脫坑!