微信小程序如何滚动到页面的顶部?
切换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()
不知道你说的
切换Tab
具体是啥场景,没在你问题中提现出来,其实只需要在
<scroll-view scroll-into-view="{{ topFlag }}">
顶部加一个
<view id="scroll-top-flag"></view>
然后在js中执行
就行了