微信小程序 利用bindscroll 实现页面滑动到顶部

效果: 当页面往下滑动一段距离(例如150px),右下角会实时出现一个圆形标签,点击会将页面滑动至顶端。

实现代码:
wxml:

<!--index.wxml-->
<scroll-view class="aa" scroll-y scroll-top='{{top}}' bindscroll="scrollgo">
<view class="cc">11111111</view>
<view class="cc">22222222</view>
<view class="cc">33333333</view>
<view class="cc">44444444</view>
<view class="cc">55555555</view>
<view class="cc">66666666</view>
<view class="cc">77777777</view>
<view class="cc">88888888</view>
 </scroll-view>

 <view class="gobtn" hidden='{{isshow}}' catchtap="goTop">
   顶部
</view>

wxss :

/**index.wxss**/

page{
  height: 100%;
  width: 100%;
}

.aa{
  width: 100%;
  height: 100%;
}

.cc{
 width: 100%;
 height: 20%;
 /* background-color: #0094ff; */
}

.gobtn{
  width: 150rpx;
  height: 150rpx;
  position: fixed;
  right: 100rpx;
  bottom: 150rpx;
  border-radius: 50%;
  text-align: center;
  line-height: 150rpx;
  border: 2px solid chartreuse;
  background-color: #0094ff;
}

js:

//index.js
//获取应用实例
const app = getApp()

Page({
  data: {
    top: 0,
    isshow: true
  },
  
  // bindscroll 滚动时会触发,然后获取滚动条当前位置
  scrollgo: function (e) {
    // console.log(e)
    if (e.detail.scrollTop > 150) {    // 滑动超过300才显示
      this.setData({
        isshow : false
      });
    } else {
      this.setData({
        isshow: true  
      });
    }
  },

  //回到顶部
  goTop: function () {  // 点击回到顶部
    this.setData({
      top: 0  // 用this.setData 才能实时更新界面
    });
  },

})  //page()

isshow 变量控制右下角的图标是否出现,例子中是滑动超过150px 出现,少于150px隐藏。

最好查看一下官方文档的说明,注意scroll-top 、 bindscroll、catchtap、hidden 的使用方法。

效果图:
在这里插入图片描述

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值