react h5安卓软键盘弹起时,底部固定元素被弹起

663 阅读1分钟

问题:安卓软键盘弹起时,会占用页面高度,导致底部固定元素被弹起,遮挡页面上部元素显示。
解决方案:安卓软键盘弹起时,会引起页面高度改变,通过监听window的onresize事件,来改变底部固定元素的显隐。

    //hooks.js 自定义hooks
    import { useState, useEffect } from 'react';
    
    export const useMonitorSoftKeyboard = () => {
        const [hideBottom, setHideBottom] = useState(false)
        useEffect(() => {
            let handleFocusIn;
            let handleFocusOut;
            let handleResize;
            const ua = window.navigator.userAgent.toLocaleLowerCase();
            const isIOS = /iphone|ipad|ipod|ios/.test(ua);
            const isAndroid = /android/.test(ua);
            if (isIOS) {
                handleFocusIn = () => {
                    setHideBottom(true)
                }
                handleFocusOut = () => {
                    setHideBottom(false)
                }
                document.body.addEventListener('focusin', handleFocusIn);
                document.body.addEventListener('focusout', handleFocusOut);
            }
            if (isAndroid) {
                const originalHeight = document.documentElement.clientHeight || document.body.clientHeight;
                handleResize = () => {
                    const resizeHeight = document.documentElement.clientHeight || document.body.clientHeight;
                    setHideBottom((originalHeight - resizeHeight) > 200);
                }
                window.addEventListener('resize', handleResize)
            }

            return () => {
                if (handleFocusIn && handleFocusOut) {
                    document.body.removeEventListener('focusin', handleFocusIn);
                    document.body.removeEventListener('focusout', handleFocusOut);
                }
                if (handleResize) {
                    window.removeEventListener('resize', handleResize)
                }
            }

        }, [])
        return hideBottom;
    }
import React from 'react'
import { useMonitorSoftKeyboard } from '../js/hooks'

const Demo = () => {
    const hideBottom = useMonitorSoftKeyboard()
    return (
        <div>
            {!hideBottom && <div>bottom content</div>}
        </div>
    )
}

export default Demo

参考文章:
blog.csdn.net/yiguoxiaoha… juejin.cn/post/716976… segmentfault.com/a/119000002…