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"三个对应元素 但此时想要始终滚动到顶部 我们可以将触发的的三个元素 设置为空
这时就能实现 点击后始终返回顶部