1.wxml
<scroll-view
scroll-y
lower-threshold="100"
id="scroller"
bindscrolltolower="scrollToLower"
bindscroll="scrollPosition"
scroll-with-animation="true" 开启动画
scroll-top="{{topPosition}}" 设置滚动到顶部的值
style="height:100vh">
<view wx:for="{{listData}}" wx:key="{{index}}">
{{item.title}}
</view>
</scroll-view>
//返回顶部按钮
<view class="toTop" hidden="{{showBackTop}}" bindtap='onBackTop'>toTop</view>
2.wxss
.toTop{
position: fixed;
right: 20rpx;
bottom: 20px;
width: 160rpx;
height: 50rpx;
background-color: red;
}
3.js
Page({
data:{
showBackTop: true,//默认隐藏
topPosition:0 //返回到的位置
},
scrollPosition(e) { //监听容器滚动
// 1.获取滚动的距离
const position = e.detail.scrollTop;
// 2.设置是否显示:滚动1000px显示‘返回顶部’按钮,否则隐藏
if(position>1000){
this.setData({
showBackTop: false,
})
}else{
this.setData({
showBackTop: true,
})
}
},
//返回顶部
onBackTop() {
// wx.pageScrollTo({
// scrollTop: 0,
// duration: 0
// })
this.setData({
showBackTop: true,
topPosition: 0
})
},
})