1.wxml
<!-- 回到顶部 -->
<scroll-view scroll-y scroll-top='{{topNum}}' bindscroll="scrolltoupper">
<view class="gotop" hidden='{{!cangotop}}' catchtap="goTop">
<view>^</view>
</view>
</scroll-view>
2.wxss
.gotop{
position:fixed;
right:30rpx;
bottom:50rpx;
height:70rpx;
width:70rpx;
border-radius: 50%;
display:flex;
flex-direction:row;
align-items:center;
justify-content:center;
text-align:center;
color:white;
font-size:21rpx;
font-weight:bold;
background:#FB5979;
}
3.js
// 获取滚动条当前位置
onPageScroll: function (e) {
if (e.scrollTop > 100) { //页面距离大于100px,则显示回到顶部控件
this.setData({
cangotop: true
});
} else {
this.setData({
cangotop: false
});
}
},
//回到顶部,内部调用系统API
goTop: function (e) { // 一键回到顶部
if (wx.pageScrollTo) {
// //wx.pageScrollTo(OBJECT)
// 基础库 1.4.0 开始支持,低版本需做兼容处理
// 将页面滚动到目标位置。
// OBJECT参数说明:
// 参数名 类型 必填 说明
// scrollTop Number 是 滚动到页面的目标位置(单位px)
// duration Number 否 滚动动画的时长,默认300ms,单位 ms
wx.pageScrollTo({
scrollTop: 0
})
} else {
wx.showModal({
title: '提示',
content: '当前微信版本过低,暂无法使用该功能,请升级后重试。'
})
}
},