微信小程序 滚动显示返回顶部

项目过程中,列表页过长,产品需求加载两屏以上才显示返回顶部的按钮,直接上代码。

这个案例设定了两个变量,一个是滚动条的高度,可能不止一个页面会用到返回顶部,所以一个是全局的获取屏幕的高度。内容部分自己定义,不赘述,本例是模拟效果。

test.wxml

<text>内容部分</text>
<view wx:if="{{scrollTop>minscreenHeight}}" class="goTop" bindtap="goTop">
   <text>返回\n顶部</text>  
</view>

test.wxss

page{ height:2000px; background: #fff;}
.goTop{width:68rpx;height:68rpx; position: fixed;bottom:30rpx; right:26rpx; z-index:4;border-radius: 50%; background: #ccc;color:#fff; font-size: 20rpx; display: flex; align-items: center;justify-content: center; }

app.js

data: {
    minscreenHeight:0,
},
 onLaunch: function () {
    this.getHeight(1)
},
  getHeight: function (n) {
    var _this = this;
    wx.getSystemInfo({
      success: function (res) {
        _this.data.minscreenHeight = res.windowHeight * n
      }
    })
  },
  goTop: function () {
    wx.pageScrollTo({
      scrollTop: 0,
      duration: 300
    })
  },

test.js调用

const app = getApp();
Page({
  data: {
    minscreenHeight: app.data.minscreenHeight,
    scrollTop: 0,
  },
  onPageScroll: function (e) { // 获取滚动条当前位置
    this.setData({
      scrollTop: e.scrollTop
    })
  },
  goTop:function(){
    app.goTop()
  },

})