移动端H5输入框调用手机软键盘,导致底部固定定位被顶起问题解决

问题描述:

部分安卓和ihpone手机在调起手机软键盘时,会将固定定位元素顶起;

产生影响:

当页面内容过多时,会导致内容被遮挡,无法查看,从而影响用户体验;

如下图所示:

解决办法:

可以监听window对象的resize事件,判断当前屏幕高度是否小于原始屏幕高度,从而来对底部定位的元素控制其显示、隐藏;

具体代码展示如下:

  
export default () => {
  const [btnShow, setBtnShow] = useState(true)

  useEffect(() => {
    // 判断当前宿主环境
    const u = navigator.userAgent
    const isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1
    const isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)

    const originalHeight = document.documentElement.clientHeight || document.body.clientHeight
    if (isAndroid || isIOS) {
      window.addEventListener('resize', () => {
        const resizeHeight = document.documentElement.clientHeight || document.body.clientHeight
        // 当前屏幕高度 < 原始屏幕高度,隐藏按钮
        if (resizeHeight < originalHeight) {
          setBtnShow(false)
        } else {
          setBtnShow(true)
        }
      })

       window.removeEventListener('resize', () => {})
    }
  }, [])

  return (
    <div>
        {btnShow && (
          <footer>
            <Button color="primary" type="submit" loading={loading}>
              确认
            </Button>
          </footer>
        )}
    </div>
  )
}

最终呈现效果:

缺陷:

         这个可以解决大部分手机的固定定位被顶起问题,但是对于部分iphone手机使用某些第三方输入法关闭事件可能监听不到。

猜你喜欢

转载自blog.csdn.net/u014165391/article/details/126409921