可以用this.scroller.currentOffset().yOffset作为滑动距离的标准,用onScrollFrameBegin回调进行监听,对滑动距离判断并进行色值变化。
@Entry @Component struct ScrollExample { scroller: Scroller = new Scroller(); private arr: number[] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; @State bgColor: string = '#FFF'; 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 }) .backgroundColor(this.bgColor); }, (item: string) => item); }.width('100%'); } .scrollable(ScrollDirection.Vertical) // 滚动方向纵向 .scrollBar(BarState.On) // 滚动条常驻显示 .scrollBarColor(Color.Gray) // 滚动条颜色 .scrollBarWidth(10) // 滚动条宽度 .friction(0.6) .edgeEffect(EdgeEffect.Spring) .onScrollFrameBegin((offset: number) => { if (this.scroller.currentOffset().yOffset > 0) { this.bgColor = '#FFF'; } if (this.scroller.currentOffset().yOffset > 300) { this.bgColor = '#999'; } if (this.scroller.currentOffset().yOffset > 600) { this.bgColor = '#333'; } return { offsetRemain: offset }; }); }.width('100%').height('100%').backgroundColor(0xDCDCDC); } }