美文网首页
H5 移动端软键盘挡住输入框

H5 移动端软键盘挡住输入框

作者: Johnson杰 | 来源:发表于2019-06-19 17:52 被阅读0次

    在移动端布局中,常见的底部有一个固定按钮,页面中有输入框
    当输入框聚焦时,底部按钮会被顶起遮住输入框

    1.功能

    输入框获焦,唤起软键盘,自动修改输入框位置,使软键盘不遮挡输入框

    1.1问题GIF

    e7fad21ec573a7489aae47362ad3e2e0.gif

    2.实现

    2.1方案

    focus事件中进行处理
    scrollIntoViewIfNeeded 和 scrollTop 结合使用

    2.2 代码实现

    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,根据 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,待验证效果!!!!
    
    /*
      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.完成效果

    72021841bcae09dcc1a0c4bf4dc6a125.gif

    参考文献,iOS下Html页面中input获取焦点弹出键盘时挡住input解决方案—scrollIntoView()

    参考文献,H5 的input 在安卓键盘弹出后被挡住所引发的

    参考文献,js 移动端之监听软键盘弹出收起

    相关文章

      网友评论

          本文标题:H5 移动端软键盘挡住输入框

          本文链接:https://www.haomeiwen.com/subject/gtnkqctx.html