【微信小程序】scroll-view实现聊天对话自动滚动到列表底部

一、在wxml中添加scroll-view

<view>
...
  <scroll-view class="scrollarea" scroll-y="true" scroll-into-view="{{bottomViewId}}" scroll-with-animation="true" 
  bindscroll="messageListScrolling" enable-back-to-top="true" type='list'>
    <view class="box" wx:for="{{content}}" wx:key="this" id="item{{index}}">
        <view class="item" wx:if="{{index%2 == 0}}">
          <view class="mineTextBox">
            <text class="mineText">{{content[index].text}}</text>
          </view>
        </view>
  
        <view class="item" wx:if="{{index%2 == 1}}">
          <view class="himTextBox">
            <text class="himText">{{content[index].text}}</text>
          </view>
        </view>
      </view>
...
</view>

scroll-view中,我添加了一个view用来包裹对话列表,这里主要通过设置scroll-y="true"允许纵向滚动croll-into-view="{{bottomViewId}}"来滚动至指定的view


二、js代码

Page({
  data: {
    bottomViewId: 0,
    content : [],
  }, 
  sendMess() {
    // 这里写你添加到messageList的代码
    content.push({
      id : 0,// 对话发送,为0
      text : "问题"
    })
    content.push({
      id : 1,// 对话回复,为1
      text : "回复"
    })
    // 定位到最后一行
    setTimeout(() => {
      that.setData({bottomViewId: `item${that.data.content.length-1}`,
    })
  }
})

三、wxss样式代码

/**chat.wxss**/
.scrollarea {
  background: linear-gradient(to bottom, #b9deff, #FFFFFF);
  width: 100%;
  max-height: 79vh;
  min-height: 744px;
  overflow: auto;
}
.box {
    width: 100%;
    display: flex;
    flex-direction: row;
    padding-top: 10px;
    margin-bottom: 2px;
}
.item {
    width: 100%;
    min-height: 50px;
    display: flex;
    flex-direction: row;
    align-items: center;
}
.mineText {
    font-size: 16px;
    color: black;
}
.himText {
    font-size: 16px;
    color: black;
}

参考

微信小程序中 scroll-view滚动条始终在最底部

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容