解决uni-app微信小程序input输入框在底部时,键盘弹起页面整体上移问题

问题描述:

最近的做了个客服聊天的功能,遇到一个问题如下:
在手机上点击聊天页底部的input框后,键盘弹起同时页面会整体上移,标题栏被顶上去了。如下图:

在这里插入图片描述

问题分析:

input 获取焦点时会自动调起手机键盘,设置 :adjust-position="true",会导致键盘弹起时页面整体上移

解决思路:

  1. 设置使键盘弹起使页面不上移
  2. 设置输入框所在盒子为绝对定位
  3. 键盘弹起时获取键盘高度
  4. 设置输入框所在盒子的bottom的键盘高度

解决方案:

注意:我这里是将消息输入部分封装成了组件,引入到它所在的 view 里的,所以需要将键盘高度子传父传值给它所在的盒子,如果是在同一个文件中的话直接将获取到的键盘高度赋值给 bottom 就可以。

1. input

<input
	class="TUI-message-input-area"
	:adjust-position="false"  // 修改为 false,使键盘弹起页面不上移
	cursor-spacing="20"
	v-model="inputText"
	@input="onInputValueChange"
	maxlength="140"
	type="text"
	placeholder-class="input-placeholder"
	placeholder="说点什么呢~"
	@focus="inputBindFocus" // 添加获取焦点键盘弹起事件
	@blur="inputBindBlur" // 添加失去焦点键盘隐藏事件
/>

重点在这里!!!我踩坑被折磨很久的一个地方!!!一定要用 px!!!

methods: {
    
    
	inputBindFocus(e) {
    
    
		// 获取手机键盘的高度,赋值给input 所在盒子的 bottom 值
		// 注意!!! 这里的 px 至关重要!!! 我搜到的很多解决方案都没有说这里要添加 px
		this.$emit('changeBottomVal',  e.detail.height + 'px')
	},
   
	inputBindBlur() {
    
    
		// input 失去焦点,键盘隐藏,设置 input 所在盒子的 bottom 值为0
		this.$emit('changeBottomVal', 0)
	}
}

2. input 所在的盒子:

<view v-if="showChat" class="message-input" :style="{ bottom: bottomVal }">
	<TUI-message-input id="message-input" ref="messageInput" :conversation="conversation" @sendMessage="sendMessage" @changeBottomVal="changeBottomVal"/>
</view>
data() {
    
    
	return {
    
    
		bottomVal: ''
	}
}
methods: {
    
    
	changeBottomVal(val) {
    
    
		this.bottomVal = val
	}
}
.message-input {
    
    
	flex-shrink: 0;
	width: 100%;
	position: absolute; // input 所在盒子设置绝对定位
	left: 0;
	bottom: 0; // 默认 0
	z-index: 199;
}

总结:

由于获取的系统的尺寸单位都是 px ,给 bottom 设置的值单位也一定要是 px ! 不能因为是手机端就用 rpx,2倍的 rpx 也不可以,因为并不是每个手机分辨率都是我们设计图上375的2倍,一定要用 px 啊!!!

猜你喜欢

转载自blog.csdn.net/xiamoziqian/article/details/125202051