实现聊天室文本信息始终在底部,并且上拉固定不滚动,下拉后自动滚动
html
<scroll-view id="scrollview" class="discuss_info" scroll-y="true" style="height:248px;overflow: auto;"
:scroll-with-animation="true" :scroll-top="scrollTop" @scroll="binddragstart">
<view class="discuss_item" v-for="(item,index) in discussList" :key="index">
<view class="user_box row" v-if="item.mess">
<text class="txt">{{item.name}}</text>
<image :src="item.levelUrl"></image>
</view>
<view class="txt user_txt" v-if="item.mess">{{item.mess}}</view>
</view>
</scroll-view>
js
stopScoll: true,
scrollHeight: 0,
scrollHighthi: 0,
binddragstart: debounce(function(e) {
//用e.detail.scrollTop这次滚动对比this.scrollHeight上次滚动来判断上拉还是下拉
if (e.detail.scrollTop < this.scrollHeight) {
this.stopScoll = false //判断是否自动滚动
} else {
this.stopScoll = true
}
this.scrollHeight = e.detail.scrollTop //上一次滚动的位置
this.myscrollHeight = e.detail.scrollHeight //获取滚动的整个高度
}, 100),
scrollToBottom: function() {
clearTimeout(this.timer)
let that = this;
let query = uni.createSelectorQuery();
query.selectAll('.discuss_item').boundingClientRect();
query.select('#scrollview').boundingClientRect();
query.exec((res) => {
if (res[0].length > 0) {
//累加最后一次追加的元素的高度,这样不用减少了foeEch循环,优化,相当于forEach一次一次累加,因为this.scrollHighthi记住了上一次的值
this.scrollHighthi += res[0][res[0].length - 1].height
if (this.myscrollHeight > this.scrollHighthi) {
//一定要用延迟,不然位置不对
this.timer = setTimeout(() => {
that.scrollTop = this.myscrollHeight
}, 10)
} else {
this.timer = setTimeout(() => {
that.scrollTop = this.scrollHighthi
}, 10)
}
}
})
},