案例:
消息列表充满屏幕的时候,底部永远要展示新消息,也就是说要让最新的数据自动向上滚动,这需要用到scroll-view的一个属性,scroll-top:设置竖向滚动条位置,效果如下:
注意:仔细阅读官网文档中关于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">
<!-- 单个消息2 本人发出(右) -->
<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>
<!-- 单个消息1 其他用户发出(左) -->
<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中计算scroll-view需要滚动到的位置
receiveMsgs: function(data) {
console.log('receiveMsgs', data);
let msgs = this.data.msgs || [];
msgs.push(data);
this.setData({
msgs: msgs
},()=>{
//确定在收到新消息的时候更新高度
this.goToBottom();
});
},
// 容器滚动到底部
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
});
});
},