問題 ios設備:點擊input,軟鍵盤彈出,頁面整體向上偏移 需求 當軟鍵盤彈起,input改變位置並始終貼著軟鍵盤,整體頁面不上移動 解決 頁面採用flex佈局 <div class="flex"> <div class="box"> <div class="head"></div> //標題區 ...
問題
ios設備:點擊input,軟鍵盤彈出,頁面整體向上偏移
需求
當軟鍵盤彈起,input改變位置並始終貼著軟鍵盤,整體頁面不上移動
解決
頁面採用flex佈局
<div class="flex"> <div class="box"> <div class="head"></div> //標題區 <div class="body"></div> //內容滾動區 <div class="foot"></div> //輸入區 </div> </div>
涉及內置API,返回一個DOMRect對象,包含left
、top
、right
、bottom
、x
、y
、width
和 height元素。
document.getBoundingClientRect()
getBoundingClientRect()是相對瀏覽器而言的,因此使用與整體頁面偏移的情況。
offset()也是可以計算偏移量,但其是相對於父元素,因此在此處不適用
setTimeout(() => { let flex = document.querySelector('.flex') //頁面向上偏移量 let changeHeight = flex.getBoundingClientRect().top //flex高度 let flexHeight =flex.offsetHeight //改變flex-div的height flex.style.height = parseInt(flexHeight + changeHeight) + 'px' } }, 100)
因為要考慮軟鍵盤彈出是動畫需要時間,所以設置定時器來暫緩代碼。為了讓效果看起來連貫,定時設置為100ms,而下麵讓頁面回滾定時為101ms。
遺留問題
當軟鍵盤彈起,頁面高度減少,但是在頁面和軟鍵盤之間會遺留一片空白區域,不知道是什麼原因,只能通過設置頁面滾動來返回初始位置
setTimeout(() => { window.scroll(0, 0) }, 101)
源碼
項目是用vue寫,並且設定了在某種條件下才處理軟鍵盤
只有ios才要處理,增加判斷打開頁面設備是否為ios
setFlexHeight() { //判斷是否為ios設備,只有ios設備有這樣的情況 const user = navigator.userAgent let isIos = !!user.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios終端 if (isIos) { setTimeout(() => { if (this.contentList.length >= 3) this.flexHeight = '100%' else { //頁面向上偏移量 let changeHeight = this.$refs.flex.getBoundingClientRect().top //flex高度 let flexHeight = this.$refs.flex.offsetHeight //改變flex-div的height this.flexHeight = parseInt(flexHeight + changeHeight) + 'px' } }, 100) //因為軟鍵盤彈起頁面縮短,導致頁面和軟鍵盤之間留白 //重新讓頁面回到底部 if (this.contentList.length < 3) { setTimeout(() => { window.scroll(0, 0) }, 101) } } }