方法一
*.wxml
<!-- 返回顶部 -->
<view class="goTop" hidden='{{!floorstatus}}' bindtap="goTop">Top</view>
*.wxss
/* 返回顶部 */
.goTop{
width: 140rpx;
height: 140rpx;
line-height: 140rpx;
text-align: center;
border-radius: 50%;
position: fixed;
bottom: 80rpx;
right: 40rpx;
z-index: 9999;
background: rgba(0,0,0,.6);
color: #fff;
font-size: 36rpx;
}
*.js
Page({
data: {
floorstatus: false
},
//回到顶部
goTop: function (e) { // 一键回到顶部
if (wx.pageScrollTo) {
wx.pageScrollTo({
scrollTop: 0, // 滚动到页面的目标位置,单位 px
duration: 2000 // 滚动动画的时长,单位 ms
})
} else {
wx.showModal({
title: '提示',
content: '当前微信版本过低,无法使用该功能,请升级到最新微信版本后重试。'
})
}
},
onPageScroll: function (e) {
if (e.scrollTop > 200) {
this.setData({
floorstatus: true
});
} else {
this.setData({
floorstatus: false
});
}
}
})
方法二
*.wxml
<scroll-view scroll-with-animation style="height: {{scrollHeight}}px" scroll-y scroll-top="{{scrollTop}}" bindscroll="scrolling" bindscrolltolower="scrolltoBtm">
//内容
//返回顶部
<view bindtap="scrollToTop" class="widget-goTop" wx:if="{{visual}}">
<image src="/pages/image/top.png"></image>
</view>
</scroll-view>
*.js
Page({
data: {
scrollHeight: wx.getSystemInfoSync().windowHeight,
visual: false,
},
scrollToTop() {
this.setData({
scrollTop: 0
})
},
scrolling(e) {
let scrollTop = e.detail.scrollTop
if (scrollTop < this.data.scrollHeight / 2) {
this.setData({
visual: false
})
} else {
this.setData({
visual: true
})
}
},
scrolltoBtm: function () {
},
})