需求:在列表页,根据滚动的距离,日期跟随。
思路:记录每次滚动的scrolltop,用watch监听当前滚动高度,每500毫秒(可以根据需求修改时间)检测一次当前列表处在哪个日期区间。
实现:
html:
<div v-if="transactionlist&&transactionlist.length > 0">
<div class="transactionlist-list">
<transaction-panel
:id="'date_label'+index"
@openDetail="onOpenDetail"
v-for="(item,index) in transactionlist"
:datas="item"
:key="index"
/>
</div>
<div class="moreTxt" v-if="!hasMoredata && !isRefresh">
没有更多了哦~
</div>
<div class="moreTxt" v-else>
<van-loading size="16">正在加载更多...</van-loading>
</div>
</div>
<div v-else-if="transactionlist&&transactionlist.length==0" class="empty-class">
<empty
:emptyImageSrc="imageSrc"
:text="emptyText"
:imageClass="imageClass"
/>
</div>
js:
import wepy from '@wepy/core';
wepy.page({
data: {
transactionlist: null,
scrollHeight:0
},
watch: {
scrollHeight(newValue, oldValue) {
clearTimeout(this.timeFn);
this.timeFn = setTimeout(async () => {
let arr = await this.getHeightFn()
arr.forEach((item, index) => {
if (newValue >= (item - arr[0])) this.monthStr = this.transactionlist[index].date_label_txt;
})
}, 500)
}
},
methods: {
getHeightFn() {
return new Promise((resolve, reject) => {
let query = wx.createSelectorQuery()
this.transactionlist.map((item, index) => {
query.select('#date_label' + index).boundingClientRect((rect) => {
item.scrollHeight = rect.top
}).exec()
})
setTimeout(() => {
let arr = this.transactionlist.map(item => item.scrollHeight)
resolve(arr);
}, 500)
})
},
},
onPageScroll (e) {
this.scrollHeight = e.scrollTop;
},
getHeightFn函数获取dom的offsettop值,并且拼成一个数组,用于检测当前高度位于哪个区间。
onPageScroll函数 是 小程序自带api,监听当前滚动高度。
用到的知识点:createSelectorQuery详细解释 onPageScroll