Scroll(this.scroller) { Column() { ForEach(this.arr, (item: number) => { Text(item.toString()) .width('90%') .height(150) .backgroundColor(0xFFFFFF) .borderRadius(15) .fontSize(16) .textAlign(TextAlign.Center) .margin({ top: 10 }); }, (item: string) => item); } .width('100%'); } .scrollable(ScrollDirection.Vertical) // Scroll滚动时触发该回调 .onDidScroll(() => { this.yOffset = this.scroller.currentOffset().yOffset; if (this.yOffset >= 1000) { this.scroller.scrollTo({ xOffset: 0, yOffset: 1000, animation: true }); } })
if (this.yOffset >= 1000) { this.scroller.scrollTo({ xOffset: 0, yOffset: 1000, animation: true }); }
完整代码如下所示:
@Entry @Component struct ScrollDemo { @State yOffset: number = 0; scroller: Scroller = new Scroller(); private arr: number[] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]; build() { Stack({ alignContent: Alignment.TopStart }) { Scroll(this.scroller) { Column() { ForEach(this.arr, (item: number) => { Text(item.toString()) .width('90%') .height(150) .backgroundColor(0xFFFFFF) .borderRadius(15) .fontSize(16) .textAlign(TextAlign.Center) .margin({ top: 10 }); }, (item: string) => item); } .width('100%'); } .scrollable(ScrollDirection.Vertical) // Scroll滚动时触发该回调 .onDidScroll(() => { this.yOffset = this.scroller.currentOffset().yOffset; if (this.yOffset >= 1000) { this.scroller.scrollTo({ xOffset: 0, yOffset: 1000, animation: true }); } }) .scrollBar(BarState.On) .scrollBarColor(Color.Gray) .scrollBarWidth(2) .friction(0.6) .edgeEffect(this.yOffset <= 0 ? EdgeEffect.Spring : EdgeEffect.None); } .width('100%') .height('100%') .backgroundColor(0xDCDCDC); } }