小程序实现点击回到顶部

方法一

*.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 () {
    //触发内容
  },
})
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值