移动端软键盘弹出 input位置顶到可视区域

当移动端软键盘弹起时,将input滚动到可视区域。

具体代码如下:

/**
 * 检测手机输入法软键盘是否弹出
 * @param {Function} cb 回调,出参true/false,分别代表键盘弹出或收起
 */
export const fn_isShowKeyboard = (cb) => {
    const winHeight = window.innerHeight;
    window.onresize = () => {
        let thisHeight = window.innerHeight;
        // 软键盘高度
        const softKeyHeight = winHeight - thisHeight;
        if (softKeyHeight > 50) {
            //当软键盘弹出,在这里面操作
            cb(true, softKeyHeight, winHeight)
        } else {
            //当软键盘收起,在此处操作
            cb(false)
        }
    }
}

/**
 * 将Focus后的input移入可见视图
 * 注: 方法中的选择器,可视页面元素情况而定
 */
export const putInputToView = () => {
    fn_isShowKeyboard((isShow, softKeyHeight, winHeight) => {
        // 父容器
        const qb_content = document.querySelector('.parent_content');
        if (!isShow) {
            qb_content.scrollTop = 0;
        };
        let dynamicHeight = '100%';
        if (isShow) {
            dynamicHeight = window.innerHeight + 'px';
        }
        const activeElement = document.activeElement,
            elType = activeElement.getAttribute('type'),
            needChangArr = ['password', 'text', 'textarea'];
        document.querySelector('body').style.height = dynamicHeight;
        if (needChangArr.indexOf(elType) > -1) {
            const elOffsetTop = activeElement.offsetTop;
            const eleHeight = activeElement.clientHeight;
            setTimeout(() => {
                const diff = winHeight - softKeyHeight;
                qb_content.scrollTop = diff  > elOffsetTop ? 0 : elOffsetTop - softKeyHeight + eleHeight;
            }, 20);
        }
    })
}
  • 在页面加载后调用
putInputToView()
展示评论