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

 

一,在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
    });
  },

 

 

 

 

  • 6
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值