1.适用场景: 页面没有使用scroll-view 组件
(这个方法让我找了好久)
wxml:(图片自己找把,我就不给了)
<image src='{{img_url}}mp/backtotop@2x.png' class='goTop' hidden='{{!floorstatus}}' bindtap="goTop"></image>wxss:
.goTop{ height: 80rpx; width: 80rpx; position: fixed; bottom: 50rpx; right: 30rpx; border-radius: 50%;}js(敲黑板):
data给个初始值:floorstatus: true,
// 获取滚动条当前位置 onPageScroll: function (e) { console.log(e) if (e.scrollTop > 150) { this.setData({ floorstatus: true }); } else { this.setData({ floorstatus: false }); } }, //回到顶部 goTop: function (e) { // 一键回到顶部 if (wx.pageScrollTo) { wx.pageScrollTo({ scrollTop: 0 }) } else { wx.showModal({ title: '提示', content: '当前微信版本过低,无法使用该功能,请升级到最新微信版本后重试。' }) } },2.页面用了scroll-view 组件
页面用了这个组件了,那你就随意了,小程序官方文档写的很清楚,获取滚动条位置。哈哈哈
wxml:
<scroll-view scroll-y scroll-top='{{topNum}}' bindscroll="scrolltoupper"><image src='../../img/button-top.png' class='goTop' hidden='{{!floorstatus}}' bindtap="goTop"></image>css: css同上
.goTop{ height: 80rpx; width: 80rpx; position: fixed; bottom: 50rpx; right: 30rpx; border-radius: 50%;}js:
data:{ topNum: 0 } // 获取滚动条当前位置 scrolltoupper:function(e){ console.log(e) if (e.detail.scrollTop > 100) { this.setData({ floorstatus: true }); } else { this.setData({ floorstatus: false }); } }, //回到顶部 goTop: function (e) { // 一键回到顶部 this.setData({ topNum: this.data.topNum = 0 }); },
2种方法已经覆盖了所有场景。看你情况选一个把。
打完收工! 关注点一下














