生活随笔
收集整理的這篇文章主要介紹了
移动端软键盘弹起遮挡输入框问题的解决方案
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
移動端軟鍵盤彈起遮擋輸入框問題的解決方案
1.背景
原生app與H5頁面混合開發時,input輸入框喚起軟鍵盤時,輸入框被遮擋,分為兩種情況:
客戶端設置了windowSoftInputMode ="adjustResize"屬性,軟鍵盤會將webview向上抬起,偶現input框被遮擋客戶端未設置windowSoftInputMode ="adjustResize"屬性,軟鍵盤在webview上方,不會將webview抬起,一直遮擋input的輸入框
針對情況1的解決方案
當webview可以被抬起時,是可以監聽到resize事件的,resize事件觸發,判斷input框是否在可視區內,在可視區內不做變動,否則計算距離后上移
監聽resize事件
let originHeight = document.documentElement.clientHeight || document.body.clientHeight;
window.addEventListener('resize', () => { // resize事件監聽,webview高度是否發生變化//加了0.3s延時,等到鍵盤完全彈起時在判斷是否被遮擋setTimeout(() =>{this.solveCoverWays();}, 300)let resizeHeight = document.documentElement.clientHeight || document.body.clientHeight;if (originHeight < resizeHeight) {if(this.scrollTopHeightVal != 0) {// 觸發滑動,鍵盤下移時,頁面回滾document.documentElement.scrollTop = -this.scrollTopHeightValthis.scrollTopHeightVal = 0}}originHeight = resizeHeight;
}, false)
是否被遮擋判斷
solveCoverWays() {// 獲取input元素底部bottom及整體高度let inputHeight = document.getElementById("inputHeight");let inputInfo = window.getComputedStyle(inputHeight, null);let inputInfoH = parseInt(inputInfo.height.replace('px',''))// 獲取文檔當前聚焦的元素const { activeElement } = document;if (!['INPUT', 'TEXTAREA'].includes(activeElement.tagName.toUpperCase())) return;const rect = activeElement.getBoundingClientRect();if (!rect) return;// 設置初始滑動高度 ,聚焦元素到頂部的距離減去可視區的高度,如果大于0,就說明被遮擋住了,此時需要滾動到可視區內let scrollHeight = 0scrollHeight = rect.bottom - (document.documentElement.clientHeight || document.body.clientHeight);// 判斷當前focus的input底部是否在document.body可視區域內if (scrollHeight > 0) {document.body.scrollTop = scrollHeight + inputInfoH;document.documentElement.scrollTop = scrollHeight + inputInfoH;this.scrollTopHeightVal = scrollHeight + inputInfoH;}
},
注意:這里實現的前提是客戶端設置了相關屬性,可以監聽到resize事件
針對情況2的解決方案
大致計算軟鍵盤的高度,在input的聚焦時,手動將整體加個padding,失焦時去掉padding,但是鍵盤抬起時,頁面滑動效果不好
總結
以上是生活随笔為你收集整理的移动端软键盘弹起遮挡输入框问题的解决方案的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。