工作生活

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

2019-07-03  本文已影响0人  章文顺
/**
 * 检测手机输入法软键盘是否弹出
 * @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()

大前端知识库收集分享 www.rjxgc.com 壹玖零Tech
搜罗各种前后端奇淫技巧,花式编程思想,日日更新,速来围观吧...

上一篇 下一篇

猜你喜欢

热点阅读