微信小程序滚动回到顶部的两种方式

效果图

一,在view形式下滚动后回到顶部 

JS代码片段:

// 获取滚动条当前位置
  onPageScroll: function (e) {
    console.log(“打印当前页面滚动的距离=”+e)

 console.log(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: '当前微信版本过低,暂无法使用该功能,请升级后重试。'
      })
    }
  },

 css样式:该控件放置于右下角。

.gotop{
position:fixed;
right:30rpx;
bottom:50rpx;
height:60rpx;
width:100rpx;
display:flex;
flex-direction:row;
align-items:center;
justify-content:center;
text-align:center;
color:white;
font-size:21rpx;
font-weight:bold;
background:#a78e72;

}

 wxml页面:catchtap阻止冒泡事件。


<view class="gotop" hidden='{{!cangotop}}'catchtap="goTop">
  <view>回到顶部</view>
</view>

2,在scroll-view形式下回到顶部

<scroll-view scroll-y scroll-top='{{topNum}}' bindscroll="scrolltoupper">
<view class="gotop" hidden='{{!cangotop}}'catchtap="goTop">
  <view>回到顶部</view>
</view>
  </scroll-view>


JS页面代码段: 

 data:{
    topNum: 0
  }

  // 获取滚动条当前位置
  scrolltoupper:function(e){
    console.log(e)
    if (e.detail.scrollTop > 100) {
      this.setData({
        cangotop: true
      });
    } else {
      this.setData({
        cangotop: false
      });
    }
  },

  //回到顶部
  goTop: function (e) {  // 一键回到顶部
    this.setData({
      topNum:0
    });
  },
扫描二维码关注公众号,回复: 2457084 查看本文章

猜你喜欢

转载自blog.csdn.net/qq_33878858/article/details/81217817