先看效果
代码:
index.js
const app = getApp()
Page({
data:{
statsuBarHeight: app.globalData.statsuBarHeight,
headHeight:40,
chatListHeight:0,
keyboardHeight:0,
messageList:[],
inutPanelHeight:50,
toView: "item0",
curMessage:"",
},
onLoad(){
this.setChatListHeight();
wx.onKeyboardHeightChange(res => { //监听键盘高度变化
this.setData({
keyboardHeight: res.height
});
this.setChatListHeight();
this.scroll2Bottom();
});
},
setChatListHeight() {
this.setData({
chatListHeight: app.globalData.sysHeight - app.globalData.statsuBarHeight - this.data.headHeight - this.data.keyboardHeight- this.data.inutPanelHeight
})
},
hideKeyboard(){
wx.hideKeyboard();
this.hideMediaPanel();
},
getInput(e){
let value = e.detail.value;
this.setData({
curMessage: value
});
},
send() {
let curMessage = this.data.curMessage;
if (curMessage.trim() === "") {
wx.showToast({
title: '请输入聊天内容',
duration: 2000,
icon: "none"
})
return;
}
let messageList = this.data.messageList;
messageList.push(curMessage);
this.setData({
curMessage:"",
messageList:messageList
})
},
})
index.json
{
"navigationStyle":"custom"
}
index.wxml
<view class="header" style="top:{{statsuBarHeight}}px">
聊天
</view>
<scroll-view class="message-list" style="top:{{statsuBarHeight+headHeight}}px;height:{{chatListHeight}}px"
scroll-y="true" scroll-into-view="{{ toView }}" bindtap="hideKeyboard">
<block wx:for="{{messageList}}" wx:key="index" wx:for-item="item">
<view>{{item}}</view>
</block>
</scroll-view>
<view class="input-panel" style="bottom:{{keyboardHeight}}px">
<input adjust-position="{{false}}" hold-keyboard="{{true}}" bindinput="getInput" value="{{curMessage}}"/>
<view class="send-btn" bindtap="send">发送</view>
</view>
index.wxss
.header{
position: fixed;
width: 100%;
border-bottom: 1px solid #dddd;
text-align: center;
height: 40px;
line-height: 40px;
}
.message-list{
position: fixed;
width:100%;
}
.input-panel {
display: flex;
background: #dddddd;
height: 50px;
position: fixed;
width:100%;
padding:0px 10px;
align-items: center;
box-sizing: border-box;
}
.input-panel input {
flex: 1;
width: 100%;
background: #ffffff;
height: 30px;
line-height: 30px;
box-sizing: border-box;
padding:0px 5px;
border-radius: 3px;
}
.send-btn {
display: inline-block;
padding: 0px 10px;
color: #fff;
background: green;
border-radius: 3px;
line-height:30px;
margin-left:5px;
}
app.js
// app.js
App({
globalData: {
statsuBarHeight:0,
sysWidth:0,
sysHeight:0,
},
onLaunch() {
const res = wx.getSystemInfoSync()
var statusbarH = res.statusBarHeight
this.globalData.statsuBarHeight=statusbarH;
this.globalData.sysWidth = res.screenWidth;
this.globalData.sysHeight = res.screenHeight;
},
})
主要思路就是,弹出键盘后,不把内容顶起来,我们监听键盘高度变化,自动设置输入框和内容的高度,已达到比较好的体验
完整版预览:
可以扫码体验: