uniapp 跟随键盘
调整页面布局避免键盘遮挡
在pages.json中配置当前页面的style,添加"app-plus": {"softinputMode": "adjustResize"}。这种方式会让页面内容自动压缩,避免键盘遮挡输入框。
"style": {
"app-plus": {
"softinputMode": "adjustResize"
}
}
监听键盘高度动态调整
通过uni.onKeyboardHeightChange监听键盘高度变化,获取到键盘高度后动态调整页面元素位置。适用于需要精确控制布局的场景。
uni.onKeyboardHeightChange(res => {
this.keyboardHeight = res.height;
// 根据键盘高度调整输入框位置
});
使用scroll-view保持输入框可见
将表单内容包裹在scroll-view组件中,设置scroll-into-view属性。当输入框聚焦时,将其ID赋值给该属性,确保输入框滚动到可视区域。
<scroll-view :scroll-into-view="scrollViewId">
<input @focus="handleFocus" />
</scroll-view>
<script>
methods: {
handleFocus(e) {
this.scrollViewId = e.target.id;
}
}
</script>
固定底部输入框处理
对于固定在底部的输入框,在键盘弹出时可能会被遮挡。可以通过CSS定位结合键盘高度监听,动态调整输入框的bottom值。
.input-footer {
position: fixed;
bottom: 0;
}
// 监听键盘高度
uni.onKeyboardHeightChange(res => {
this.footerBottom = res.height > 0 ? res.height + 'px' : '0';
});
第三方插件解决方案
考虑使用uni-app社区的键盘处理插件,如uni-starter中的键盘处理模块。这些插件通常封装了更完善的键盘适配方案,适合复杂场景。
平台差异处理
iOS和Android的键盘行为存在差异。在manifest.json中可配置平台特定的键盘控制参数,如"softinputNavBar": "none"可隐藏Android键盘上方的导航条。
"app-plus": {
"distribute": {
"android": {
"softinputNavBar": "none"
}
}
}






