问题现象
表单页面点击输入框,键盘弹起后:
| 平台 | 表现 |
|---|---|
| 安卓 | 输入框位置错位,光标飘到其他位置 |
| iOS | 键盘遮挡输入框,看不到输入内容 |
问题原因
当页面同时存在以下三个因素时,容易出现布局错乱:
scroll-view + float布局 + fixed定位 = 💥 冲突- scroll-view:内部滚动与 input 的 adjust-position 机制冲突
- float 布局:影响后续元素的位置计算
- fixed 按钮:在 scroll-view 内部导致滚动区域计算错误
解决方案
核心思路
使用flex 布局,将固定元素移到 scroll-view 外部。
页面结构
┌──────────────────────┐ │ page-wrapper │ ← flex容器, 100vh │ ┌────────────────┐ │ │ │ scroll-view │ │ ← flex:1, 可滚动 │ │ 表单内容 │ │ │ └────────────────┘ │ │ ┌────────────────┐ │ │ │ 底部按钮 │ │ ← 固定高度,不滚动 │ └────────────────┘ │ └──────────────────────┘Demo 代码
WXML:
<viewclass="page-wrapper"><scroll-viewscroll-yclass="scroll-area"><viewclass="form"><inputplaceholder="请输入姓名"cursor-spacing="120"/><inputplaceholder="请输入手机号"cursor-spacing="120"/></view></scroll-view><viewclass="footer"><buttontype="primary">提交</button></view></view>WXSS:
.page-wrapper{display:flex;flex-direction:column;height:100vh;}.scroll-area{flex:1;}.footer{padding:20rpx 32rpx;padding-bottom:calc(20rpx +env(safe-area-inset-bottom));}关键配置
input 属性
<inputcursor-spacing="120"adjust-position="true"/>cursor-spacing: 光标与键盘距离,建议 100-150adjust-position: 键盘弹起时自动调整页面
清除浮动
如果表单有浮动元素,后续元素需清除:
.after-float-item{clear:both;}方案对比
| 方案 | 做法 | 结果 |
|---|---|---|
| ❌ 错误 | fixed 按钮放在 scroll-view 内 | 滚动异常、位置错乱 |
| ❌ 错误 | 移除 scroll-view 用原生滚动 | 页面回弹、边距异常 |
| ✅ 正确 | flex 布局 + 按钮移到外部 | 滚动正常、键盘正常 |
总结
遇到表单页面键盘问题,记住三点:
- 不要在 scroll-view 内用 fixed
- 使用flex 布局分割滚动区和固定区
- 配置cursor-spacing 保持输入框可见