案例:
消息列表充滿屏幕的時(shí)候汁展,底部永遠(yuǎn)要展示新消息滔蝉,也就是說要讓最新的數(shù)據(jù)自動(dòng)向上滾動(dòng)勿她,這需要用到scroll-view的一個(gè)屬性适荣,scroll-top:設(shè)置豎向滾動(dòng)條位置,效果如下:
注意:仔細(xì)閱讀官網(wǎng)文檔中關(guān)于scroll-view的特性介紹[https://developers.weixin.qq.com/miniprogram/dev/component/scroll-view.html](https://developers.weixin.qq.com/miniprogram/dev/component/scroll-view.html)
1苹享、WXML中的scroll-view
<scroll-view class="scorllView" scroll-top="{{scrollTop}}" scroll-y scroll-with-animation>
<view class="msgList">
<block wx:key wx:for='{{msgs}}' wx:for-index="index">
<!-- 單個(gè)消息2 本人發(fā)出(右) -->
<view wx:if='{{item.fromAccountNick==identifier}}' id='msg-{{index}}' class='viewServerRight'>
<view class='userStyleRight'>
<text class='rightMsg' selectable="{{true}}">{{item.content}}</text>
</view>
<view class='viewImgRight'>
<image class="viewImageRight" src="{{item.fromAccountHeadurl}}"></image>
</view>
</view>
<!-- 單個(gè)消息1 其他用戶發(fā)出(左) -->
<view wx:else id='msg-{{index}}' class='viewServerLeft'>
<view class='viewImg'>
<image class='viewImage' src="{{item.fromAccountHeadurl }}"></image>
</view>
<view class="userStyle">
<view class='userLeft'>{{item.fromAccountNick}}</view>
<text class='leftMsg' selectable="{{true}}">{{item.content}}</text>
</view>
</view>
</block>
</view>
</scroll-view>
2双絮、JS中計(jì)算scroll-view需要滾動(dòng)到的位置
receiveMsgs: function(data) {
console.log('receiveMsgs', data);
let msgs = this.data.msgs || [];
msgs.push(data);
this.setData({
msgs: msgs
},()=>{
//確定在收到新消息的時(shí)候更新高度
this.goToBottom();
});
},
// 容器滾動(dòng)到底部
goToBottom() {
const query = wx.createSelectorQuery().in(this);
query.select('.scorllView').boundingClientRect();
query.select('.msgList').boundingClientRect();
query.exec(res => {
const scorllHeight = res[0].height;
const listHeight = res[1].height;
this.setData({
scrollTop: listHeight - scorllHeight
});
});
},