H5移動端 input輸入完成後頁面底部留白問題
阿新 • • 發佈:2020-11-25
說明
最近在用vue寫幾個H5頁面在微信上展示,遇到一個在彈窗上input輸入完成之後點選鍵盤的完成,頁面底部留出一片空白的問題
出現原因分析
當鍵盤抬起時,window.scrollY會從0變到鍵盤的高度,所以解決辦法就是當input失去焦點的時候,將window.scrollY重新設定為0
解決
給所有的input`textarea元件設定獲取焦點和設定焦點事件,失去焦點的時候將`window.scrollY`設定為0,因為的是vue所以結合vue來寫程式碼
<template>
<input class="m-input" :value="value" @input="$emit('input', $event.target.value)" @focus="inputFocus()" @focusout="inputFocusOut">
</template>
<script>
export default {
name: "MInput",
props:['value'],
data(){
return{
timer:null
}
},
methods:{
inputFocus(){
if(this.timer){
clearTimeout(this.timer)
}
},
inputFocusOut(){
this.timer = setTimeout(() => {
window.scrollTo(0,0)
},10)
}
},
destroyed(){
if(this.timer){
clearTimeout(this.timer)
}
}
}
</script>
獲取焦點事件,判斷定時器是否存在如果存在的話清除掉(上一個input設定的定時器),失去焦點事件,將window.scrollY設定為0,並且給一個10的定時器,減少頁面失去焦點的突兀感(為了順滑一點點)
destroyed vue元件中如果使用了定時器,一定要記得在元件銷燬的生命週期裡將清時期清除掉,防止全域性定時器過多,容易爆棧
補充:解決方案2
在input上分別增加focus和blur的方法,基本可以解決鍵盤迴落後留白問題;
handleFocus(event) {
let e = event.currentTarget;
setTimeout(() => {
e.scrollIntoView({
block: 'start',
behavior: 'smooth'
});
}, 300);
}
handleblur() {
let e = event.currentTarget;
setTimeout(() => {
e.scrollIntoView({
block: 'end',
behavior: 'smooth'
});
}, 300);
window.scrollTo(0, 0);
}
補充:解決方案3
//解決鍵盤彈出後擋表單的問題
window.addEventListener('resize', function() {
if(
document.activeElement.tagName === 'INPUT' ||
document.activeElement.tagName === 'TEXTAREA'
) {
window.setTimeout(function() {
if('scrollIntoView' in document.activeElement) {
document.activeElement.scrollIntoView();
} else {
document.activeElement.scrollIntoViewIfNeeded();
}
}, 0);
}
});
廣州VI設計公司https://www.houdianzi.com
補充:頁面來回彈跳
問題:失焦時的scrollTop=0造成的頁面彈跳。本來iOS是做了這方面的優化,在軟鍵盤彈出和收起時頁面會smooth的平滑,由於我加了scrollIntoView破壞了原生的優化導致彈跳了
解決:
handleFocus(event) {
clearTimeout(this.timer);
}
handleblur() {
this.timer = setTimeout(() => {
document.body.scrollTop = 0;
window.pageXOffset = 0;
document.documentElement.scrollTop = 0;
}, 100);
}