【微信小程序】scroll-view實(shí)現(xiàn)聊天對(duì)話自動(dòng)滾動(dòng)到列表底部

一、在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中,我添加了一個(gè)view用來包裹對(duì)話列表,這里主要通過設(shè)置scroll-y="true"允許縱向滾動(dòng)croll-into-view="{{bottomViewId}}"來滾動(dòng)至指定的view


二、js代碼

Page({
  data: {
    bottomViewId: 0,
    content : [],
  }, 
  sendMess() {
    // 這里寫你添加到messageList的代碼
    content.push({
      id : 0,// 對(duì)話發(fā)送,為0
      text : "問題"
    })
    content.push({
      id : 1,// 對(duì)話回復(fù),為1
      text : "回復(fù)"
    })
    // 定位到最后一行
    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滾動(dòng)條始終在最底部

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容