問題
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) } } }
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/517646.html
標籤:JavaScript
上一篇:JS執行機制
