微信小程序如何滚动到页面的顶部?

微信小程序如何滚动到页面的顶部?

切换Tab是页面底部有四个按钮,每次点击会切换currentTab的值,然后页面的中间部分内容是更具Tab的切换而变化的,同时执行滚动到顶部的内容是在切换Tab的方法中进行的。

尝试过的方法1,无法在切换Tab的时候滚动到顶部

wx.pageScrollTo({
     scrollTop: 0,
     duration: 300 // 动画时长,单位为毫秒,可根据需求调整
});

尝试过的方法2,无法在切换Tab的时候滚动到顶部

<scroll-view scroll-y="true" bindscroll="scrolltoupper" scroll-top="{{topNum}}" style="height: 100vh;" id="myScrollView">
  ...
</scroll-view>

Page({
  data: {
    topNum: 0,
    cangotop: false
  },
  // 获取滚动条当前位置
  scrolltoupper(e) {
    console.log(e);
    if (e.detail.scrollTop > 100) {
      this.setData({
        cangotop: true
      });
    } else {
      this.setData({
        cangotop: false
      });
    }
  },
  onChangeTab() {
    this.goTop();
  },
  // 回到顶部
  goTop() {
    this.setData({
      topNum: 0
    });
  }
});

尝试过的方法3,无法在切换Tab的时候滚动到顶部

<scroll-view scroll-y="true" style="height: 100vh;" id="myScrollView">
  ...
</scroll-view>

const query = wx.createSelectorQuery()
      query.select('#myScrollView').scrollOffset(res => {
          if (res.scrollTop > 0) {
              this.setData({ topNum: 0 })
        }
}).exec()
阅读 368
1 个回答

不知道你说的切换Tab具体是啥场景,没在你问题中提现出来,
其实只需要在<scroll-view scroll-into-view="{{ topFlag }}">顶部
加一个<view id="scroll-top-flag"></view>
然后在js中执行

this.setData(
  // 先置为空
  { topFlag: '' },
  // 然后再设置为顶部flag的id
  () => this.setData({ topFlag: 'scroll-top-flag' })
)

就行了

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题