微信小程序怎么写一个聊天界面代码
时间: 2024-06-11 18:08:50 浏览: 102
微信小程序聊天功能的示例代码
微信小程序聊天界面代码示例:
wxml文件:
```
<!-- 聊天界面 -->
<view class="chat-box">
<!-- 聊天内容 -->
<scroll-view class="chat-content" scroll-y="true" scroll-into-view="{{scrollIntoView}}">
<view wx:for="{{chatList}}" wx:key="{{index}}" class="chat-item {{item.type}}">
<view wx:if="{{item.type === 'left'}}" class="avatar-wrap">
<image src="{{item.avatar}}" class="avatar" />
</view>
<view class="chat-text-wrap">
<view class="triangle {{item.type}}"></view>
<view class="chat-text">{{item.content}}</view>
</view>
<view wx:if="{{item.type === 'right'}}" class="avatar-wrap">
<image src="{{item.avatar}}" class="avatar" />
</view>
</view>
</scroll-view>
<!-- 输入框 -->
<view class="input-box">
<input class="input" placeholder="请输入聊天内容" value="{{inputValue}}" bindinput="bindInputValue" />
<button class="send-btn" bindtap="sendMsg">发送</button>
</view>
</view>
```
wxss文件:
```
.chat-box {
height: 100%;
display: flex;
flex-direction: column;
}
.chat-content {
flex: 1;
padding: 10rpx;
box-sizing: border-box;
}
.chat-item {
display: flex;
flex-direction: row;
margin-bottom: 10rpx;
}
.chat-text-wrap {
position: relative;
max-width: 60%;
}
.triangle {
position: absolute;
width: 0;
height: 0;
border-top: 5rpx solid transparent;
border-bottom: 5rpx solid transparent;
}
.triangle.left {
left: -5rpx;
border-right: 5rpx solid #fff;
}
.triangle.right {
right: -5rpx;
border-left: 5rpx solid #007aff;
}
.chat-text {
padding: 5rpx 10rpx;
background-color: #fff;
border-radius: 5rpx;
}
.avatar-wrap {
margin-right: 10rpx;
}
.avatar {
width: 50rpx;
height: 50rpx;
border-radius: 50%;
}
.input-box {
display: flex;
flex-direction: row;
align-items: center;
padding: 10rpx;
box-sizing: border-box;
background-color: #f5f5f5;
}
.input {
flex: 1;
height: 60rpx;
line-height: 60rpx;
padding: 0 20rpx;
box-sizing: border-box;
background-color: #fff;
border-radius: 30rpx;
font-size: 28rpx;
}
.send-btn {
margin-left: 20rpx;
width: 120rpx;
height: 60rpx;
line-height: 60rpx;
background-color: #007aff;
color: #fff;
border-radius: 30rpx;
font-size: 28rpx;
text-align: center;
}
```
js文件:
```
Page({
data: {
chatList: [], // 聊天记录列表
inputValue: '', // 输入框的值
scrollIntoView: '' // 滚动到的位置
},
onLoad: function () {
// 初始化聊天记录
this.setData({
chatList: [{
avatar: '/images/avatar1.png',
type: 'left',
content: '你好,欢迎来到聊天室!'
}]
})
},
// 输入框输入内容
bindInputValue: function (e) {
this.setData({
inputValue: e.detail.value
})
},
// 发送消息
sendMsg: function () {
let inputValue = this.data.inputValue.trim()
if (!inputValue) {
return
}
let chatList = this.data.chatList
chatList.push({
avatar: '/images/avatar2.png',
type: 'right',
content: inputValue
})
this.setData({
chatList: chatList,
inputValue: '',
scrollIntoView: 'chat-item-' + (chatList.length - 1)
})
}
})
```
阅读全文