React移动端唤起软键盘页面上移底部留白如何解决
移动端软键盘弹出页面上移、底部空白问题修复
问题复现
在React项目中实现响应式登录注册页时,移动端点击输入框唤起软键盘后,页面整体内容上移,底部出现空白区域,此前尝试给.login容器设置min-height: auto未生效。
- 页面初始正常展示效果:

- 软键盘弹出异常效果:

关联样式代码
.login容器原有样式:
.login{ @include flex(unset, unset); justify-content: space-between; width:100%; height: 100vh; background-color: $main-color; @include media(tablet,mobile){ min-height: auto; flex-direction: column; justify-content: unset; } }
导航栏.nav_bar原有样式:
.nav_bar{ height:100vh; width: 75px; background-color:#2e2e2e; z-index: 9; @include media(tablet, mobile){ position: fixed; bottom: 0; height: 65px; width: 100%; } }
问题原因
移动端软键盘弹出时,多数浏览器不会动态修改100vh对应的高度值,100vh始终取软键盘弹出前的全屏高度,配合justify-content: space-between的布局规则,内容会被自动推到容器上部,软键盘遮挡的区域就会显示为空白。固定在底部的导航栏也会因为视口高度计算偏差出现错位。
修复步骤
1. CSS层面替换视口单位
将移动端场景下.login容器的固定100vh高度替换为动态视口单位100dvh,该单位会自动跟随软键盘弹出/收起调整实际可用高度,同时移除不生效的min-height: auto配置:
.login{ @include flex(unset, unset); justify-content: space-between; width:100%; height: 100vh; background-color: $main-color; @include media(tablet,mobile){ /* 替换原min-height: auto配置 */ height: 100dvh; flex-direction: column; justify-content: flex-start; } }
针对不支持dvh单位的旧版浏览器,增加降级兼容规则:
@supports not (height: 100dvh) { .login { @include media(tablet,mobile){ height: calc(var(--app-height, 100vh)); } } }
2. JS层面兼容旧浏览器
在项目入口组件中监听视口尺寸变化,手动计算软键盘弹出后的实际可用高度,写入CSS全局变量供降级规则使用:
// App.jsx 入口组件 import { useEffect } from 'react'; function App() { useEffect(() => { const setActualAppHeight = () => { const visibleHeight = document.documentElement.clientHeight; document.documentElement.style.setProperty('--app-height', `${visibleHeight}px`); } // 初始化高度 setActualAppHeight(); // 监听窗口变化(软键盘弹出/收起、屏幕旋转都会触发) window.addEventListener('resize', setActualAppHeight); return () => window.removeEventListener('resize', setActualAppHeight); }, []) // 原有组件逻辑 return <div className="app">{/* 路由等业务内容 */}</div> }
3. 避免底部导航栏错位
软键盘弹出时,固定在底部的导航栏会跟随视口计算错位,可通过输入框的聚焦/失焦事件控制导航栏临时隐藏:
.nav_bar{ height:100vh; width: 75px; background-color:#2e2e2e; z-index: 9; @include media(tablet, mobile){ position: fixed; bottom: 0; height: 65px; width: 100%; /* 软键盘弹出时隐藏 */ &.hidden-when-keyboard-show { display: none; } } }
输入框聚焦时给导航栏添加hidden-when-keyboard-show类名,失焦时移除即可。
内容的提问来源于stack exchange,提问作者Carl
相关产品推荐
相关产品推荐

