点击返回顶部按钮时,使用scrollTo或scrollEdge来实现滚动到顶部,并同时设置滚动动画效果。
@Entry
@Component
struct ListExample {
private arr: number[] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20];
private scroller: Scroller = new Scroller();
build() {
Column() {
List({ space: 20, initialIndex: 0, scroller: this.scroller }) {
ForEach(this.arr, (item: number) => {
ListItem() {
Text('' + item)
.width('100%')
.height(100)
.fontSize(16)
.textAlign(TextAlign.Center)
.borderRadius(10)
.backgroundColor(0xFFFFFF)
}
}, (item: string) => item)
}
.listDirection(Axis.Vertical) // 排列方向
.scrollBar(BarState.Off)
.friction(0.6)
.edgeEffect(EdgeEffect.Spring) // 边缘效果设置为Spring
.onAppear(() => {
this.scroller.scrollToIndex(0, false, ScrollAlign.CENTER);
})
.width('90%')
.height('94%')
Button('返回顶部')
.onClick(() => {
this.scroller.scrollTo({
// 设置滚动到顶部,并配置动画
xOffset: 0, yOffset: 0, animation: {
duration: 1000
}
});
})
.margin(3)
}
.width('100%')
.height('100%')
.backgroundColor(0xDCDCDC)
.padding({ top: 5 })
}
}