# 5.聊天室功能 - 聊天的基本功能
# (1).发消息
// 聊天功能 发消息
$('.btn-send').on('click', () => {
// 获取到聊天的内容
var content = $('#content').val().trim()
$('#content').val('')
if(!content) return alert('请输入内容 ')
// 发送给服务器
socket.emit('sendMesssage',{
msg: content,
username: username,
avatar: avatar
})
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
# (2).接收消息
// 监听群聊 接收消息
socket.on('receiveMessage',data=>{
console.log(data)
// 把接收到的消息显示到聊天窗口中
// 判断当前用户是不是自己
if(data.username === username) {
// 自己的消息
}else {
// 别人的消息
}
// 解决滚动到底部的问题
// 当前元素的底部滚动到可视区
$('.box-bd').children(':last').get(0).scrollIntoView(false)
})
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