利用 scroll-view 组件实现抖音小程序返回顶部

scroll-view可滚动视图区域,可实现横向滚动和竖向滚动。那么在竖向滚动时 该如何返回顶部呢?文档给出了 scroll-into-view 属性 (为某子元素 id(id 不能以数字开头)。设置哪个方向可滚动,则在哪个方向滚动到该元素。)

这时可以使用以下代码

<scroll-view scroll-y="{{true}}" class="pro-wrap" scroll-with-animation="{{true}}" style="height: 100%" lower-threshold="{{50}}" bindscrolltolower="lower" bindscroll="scroll" scroll-into-view="{{toView}}" scroll-top="{{scrollTop}}">
 <view id="demo1"></view>
 <view id="demo2"></view>
 <view id="demo3"></view>

</scroll-view>
<view class="tool-item" bindtap="handleTap">
    <text class="iconfont icon-keyboardarrowup" style="font-size: 25px;"></text>
</view>
const order = ["demo1", "demo2", "demo3"];
Page({
  data: {
    toView: "demo1",
    scrollTop: 0,
  },
  lower(e) {
    tt.showToast({
      title: '到最底部了',
      icon: 'none'
    });
  },

  scroll(e) {},
  scrollToTop(e) {
    this.setData({
      scrollTop: 0,
    });
  },
  tap(e) {
    for (var i = 0; i < order.length; ++i) {
      if (order[i] === this.data.toView) {
        this.setData({
          toView: order[i < order.length - 1 ? i + 1 : 0],
        });
        break;
      }
    }
  },

});

这时运行的结果 点击会触发滚动到"demo1", "demo2", "demo3"三个对应元素  但此时想要始终滚动到顶部 我们可以将触发的的三个元素 设置为空 

这时就能实现 点击后始终返回顶部

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值