為什么?
為什么要隨時監測屏幕大小,這是因為我們在手機端的時候,常常會遇到這樣的問題:當點擊輸入框的時候,手機的鍵盤就會自動浮現,它會使得頁面的可視示高度(document.body.clientHeight)發生變化。而我們的輸入框就被可憐的遮擋在小鍵盤后面
怎么辦?
我們不知道小鍵盤何時會出現,但有一點是可以確定的,當小鍵盤出現的時候,body的可視區域一定為發生變化!!當我們檢測到頁面的可視高度發生了變化,我們就可以確定手機的鍵盤出來了。於是我們就可以使用document.getElementById('×××××').scrollIntoView();把被小鍵盤遮擋住的輸入框給上移到可視區域。
Ps:結合scrollIntoView()使用的還有activeElement,當我們頁面有多個input輸入框時,我們可以使用HTML5的輔助管理DOM功能,document.activeElement屬性始終會引用DOM當前獲得的焦點元素。可以獲得當前用戶焦點的元素。
document.activeElement.scrollIntoView();
監測手機小鍵盤彈出代碼:
window.onresize = () => {
// 注意,return返回的函數為立即執行函數!!
return (() => {
window.screenHeight = document.body.clientHeight;
this.showHeight = window.screenHeight;
})()
}
當我拿到showHeight,在vue里,我就可以通過watch他的變化,然后再執行相應的邏輯代碼,使用Vue.js完整代碼如下:
data() {
return {
// 默認屏幕高度
docmHeight: document.documentElement.clientHeight,
showHeight: document.documentElement.clientHeight,
}
// 渲染后執行
mounted() {
window.onresize = () => {
return (() => {
window.screenHeight = document.body.clientHeight;
this.showHeight = window.screenHeight;
})()
}
},
watch: {
showHeight: 'inputType',
},
methods: {
// 檢測屏幕高度變化
inputType() {
if (!this.timer) {
this.timer = true
let that = this
setTimeout(() => {
if (that.docmHeight > that.showHeight) {
that.inputfile = false;
if (document.activeElement.className === 'weui-textarea') {
document.getElementById('applyNote').scrollIntoView(); // 輸入框的id為applyNote,class為weui-textarea
}
} else if (that.docmHeight <= that.showHeight) {
that.inputfile = true;
}
that.timer = false;
}, 20)
}
}
}
