Browse Source

修复接收消息无法自动滚动到最新消息的问题

pull/12/head
徐飞洋 2 months ago
parent
commit
0a7f6afbb1
  1. 68
      pages/chat-detail/index.js

68
pages/chat-detail/index.js

@ -190,17 +190,67 @@ Page({
this.setData({
messages: newMessages
}, () => {
// 检查是否需要滚动到底部
if (this.data.isAtBottom) {
this.scrollToBottom(true);
} else {
// 显示新消息提示
this.setData({
hasNewMessages: true,
newMessageCount: this.data.newMessageCount + 1
});
// 检查页面是否已卸载
if (this.isUnloaded) {
console.log('页面已卸载,忽略滚动和新消息检测');
return;
}
// 重新计算是否在底部
wx.createSelectorQuery().in(this)
.select('#chatScrollView')
.boundingClientRect()
.exec((rects) => {
if (rects && rects[0]) {
const scrollViewRect = rects[0];
// 获取scroll-view的滚动信息
wx.createSelectorQuery().in(this)
.select('#chatScrollView')
.scrollOffset()
.exec((scrollOffsets) => {
if (scrollOffsets && scrollOffsets[0]) {
const { scrollTop } = scrollOffsets[0];
// 计算滚动内容的总高度
wx.createSelectorQuery().in(this)
.select('.chat-messages')
.boundingClientRect()
.exec((messageRects) => {
if (messageRects && messageRects[0]) {
const messagesHeight = messageRects[0].height;
const clientHeight = scrollViewRect.height;
// 计算滚动位置与底部的距离
const distanceToBottom = messagesHeight - scrollTop - clientHeight;
// 当距离底部小于100rpx(约50px)时,视为在底部
const isActuallyAtBottom = distanceToBottom < 50;
console.log('接收消息时的滚动检测:', {
scrollTop,
messagesHeight,
clientHeight,
distanceToBottom,
isActuallyAtBottom
});
// 如果在底部,自动滚动到最新消息
if (isActuallyAtBottom) {
this.scrollToBottom(true);
} else {
// 否则显示新消息提示
this.setData({
hasNewMessages: true,
newMessageCount: this.data.newMessageCount + 1
});
}
}
});
}
});
}
});
// 短暂延迟后移除isNew标记
setTimeout(() => {
if (this.isUnloaded) return;

Loading…
Cancel
Save