wxml
<view id="targetView">
<view class="item" wx:for="{{arr}}" wx:key="index" style="width: 100%;height: 200rpx;margin-top: 20rpx;background-color: pink;">
{{item}}
</view>
</view>
<view wx:if="{{btnShow}}" bind:tap="scrollTargetViewInfo" style="position: fixed;bottom: 200rpx;right: 50rpx;background-color: blue;border-radius: 20rpx;padding:5rpx 20rpx;color: #ffffff;">回到顶部</view>
js
Page({
data: {
arr: ['111', '222', '333', '444', '555', '666', '777', '888', '999', '101010', '111111', '121212', '131313', '141414'],
btnShow: false,
targetViewHeight: 0
},
onLoad() {
this.getTargetViewInfo();
},
getTargetViewInfo() {
const query = wx.createSelectorQuery();
query.selectAll('.item').boundingClientRect((rect) => {
if (rect[8]) {
this.setData({
targetViewHeight: rect[8].top + rect[8].height - wx.getSystemInfoSync().windowHeight
});
}
}).exec();
},
onPageScroll(event) {
const {
scrollTop
} = event;
console.log('this.data.targetViewTop',this.data.targetViewHeight,scrollTop)
if (scrollTop >= this.data.targetViewHeight) {
this.setData({
btnShow: true
});
} else {
this.setData({
btnShow: false
});
}
},
scrollTargetViewInfo() {
wx.pageScrollTo({
scrollTop: 0,
duration: 300
});
}
});