小程序键盘弹起后顶起自定义导航问题
本项目使用uni-app开发。
# bug描述
聚焦input或textarea组件时,键盘弹起会将自定义导航栏顶上去,小程序自带的不会。
# bug解决
参考软键盘弹起时页面上移 (opens new window)的思路,解决如下:
- 设置
adjust-position
属性为false。 - 监听
keyboardheightchange
事件,获取键盘高度。使用eventbus触发自定义事件keyboradChange。
- 监听blur事件,使用eventbus触发
keyboradChange
。 - 在页面最外层监听
keyboradChange
,设置页面的padding-bottom
。
完成。下面总结下
# 总结
- 微信小程序提供2中键盘弹起方式,通过
adjust-position
来控制。- 为
true
时,会自动上推页面,这个对于Input而言是符合用户预期的。因为通常用户输入的时候,希望可以实时看到输入后的文字。但缺点也很明显,它会将自定义导航也当做页面的一部分,会推出视图。 - 如果为
false
,键盘就相当于固定定位,如果input在最底部,则会被遮挡。
- 为
- 采用第二种方式来hack。需要做的是将input抬起来,前提是要知道键盘的高度。官方提供了
bindfocus
和bindkeyboardheightchange
两种方式来获取键盘高度。 - 只需要将页面设置
padding-bottom
为键盘高度,就可以控制input的位置了。
代码如下:
<textarea
v-model="msg"
class="textarea"
type="text"
confirm-type="send"
cursor-spacing="15"
auto-height
:adjust-position="false"
:show-confirm-bar="false"
placeholder-class="textarea-placeholder"
:placeholder="placeholder"
maxlength="300"
@keyboardheightchange="onkeyboardheightchange"
@blur="onBlur"
/>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15
onkeyboardheightchange(e) {
uni.$emit('keyboradChange', e.detail.height)
},
onBlur() {
uni.$emit('keyboradChange', 0)
},
1
2
3
4
5
6
2
3
4
5
6
<template>
<div class="chat-wrap" :style="{ paddingBottom: keyboradHeight + 'px' }">
<Head />
<MainView/>
<InputView/>
</div>
</template>
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
// 设置页面padding-bottom
data() {
return {
keyboradHeight: 0
}
},
onShow() {
// 处理键盘弹起后顶起自定义导航栏的问题
this.keyboradHeight = 0
uni.$on('keyboradChange', e => {
this.keyboradHeight = e
})
},
1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
上次更新: 2021/11/04, 20:03:22