在移動端布局中信粮,常見的底部有一個固定按鈕到旦,頁面中有輸入框
當輸入框聚焦時简逮,底部按鈕會被頂起遮住輸入框
1.功能
輸入框獲焦丽已,喚起軟鍵盤,自動修改輸入框位置买决,使軟鍵盤不遮擋輸入框
1.1問題GIF
2.實現(xiàn)
2.1方案
focus事件中進行處理
scrollIntoViewIfNeeded 和 scrollTop 結(jié)合使用
2.2 代碼實現(xiàn)
onFocus (index) {
// 獲取對應事件的 input dom
const inputDom = this.$refs['input' + index][0];
setTimeout(() => {
// px to rem 的比例
const rate = (window.screen.width || document.documentElement.clientWidth) / 375;
// 底部按鈕 375基準 的高度為 56沛婴,根據(jù) rate 計算實際高度
const bottomFixHeight = 56 * rate;
// 高度計算
const clientHeight = document.documentElement.clientHeight;
const top = inputDom.getBoundingClientRect().top;
const diff = clientHeight - top;
// scrollIntoViewIfNeeded 無法處理 input 和 底部按鈕重合的部分
// input 在 button 上方吼畏,或者 input 與 button 重合,修改外層 scrollTop
// input 在 button 下方嘁灯,使用 scrollIntoViewIfNeeded
if (diff >= 0 && diff < bottomFixHeight) {
this.$refs.topDom.scrollTop = this.$refs.topDom.scrollTop + bottomFixHeight * 3;
} else {
inputDom.scrollIntoViewIfNeeded(true);
}
}, 200);
},
// note 2019.08.22
// 此方法使用 requestAnimationFrame泻蚊,以及 scrollIntoView,待驗證效果3笮觥P孕邸!羹奉!
/*
Detect and load appropriate clock setting for the execution environment
*/
const hasRAF = typeof window !== 'undefined' && window.requestAnimationFrame !== undefined;
let prevTime = 0;
const onNextFrame = hasRAF
? (callback) => window.requestAnimationFrame(callback)
: (callback) => {
const currentTime = Date.now();
const timeToCall = Math.max(0, 16.7 - (currentTime - prevTime));
prevTime = currentTime + timeToCall;
setTimeout(() => callback(prevTime), timeToCall);
};
export default onNextFrame;
onFoucs(e) {
onNextFrame(() => {
e.target.scrollIntoView({
block: 'center',
inline: "nearest"
});
});
},
3.完成效果
參考文獻秒旋,iOS下Html頁面中input獲取焦點彈出鍵盤時擋住input解決方案—scrollIntoView()
參考文獻诀拭,js 移動端之監(jiān)聽軟鍵盤彈出收起