示例代码如下:
import display from '@ohos.display'; import { window } from '@kit.ArkUI'; import { BusinessError } from '@kit.BasicServicesKit'; @Entry @Component struct TabTopScroll { arr: number[] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]; @State opacityNum: number = 0; scrollSum: number = 0; @State safeTopHeight: number = 0; uiContext = this.getUIContext(); aboutToAppear(): void { let type = window.AvoidAreaType.TYPE_SYSTEM; try { window.getLastWindow(this.uiContext?.getHostContext(), (err: BusinessError, windowClass) => { const errCode: number = err.code; if (errCode) { console.error(`Failed to obtain the top window. Cause code: ${err.code}, message: ${err.message}`); return; } let avoidArea = windowClass.getWindowAvoidArea(type); let screenInfo = display.getDefaultDisplaySync(); this.safeTopHeight = avoidArea.topRect.height / screenInfo.densityPixels; }); } catch (exception) { console.error(`Failed to obtain the top window. Cause code: ${exception.code}, message: ${exception.message}`); } } build() { Column() { Flex() { } .padding({ left: 10, right: 10, bottom: this.safeTopHeight, top: 10 }) .width('100%') .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.TOP, SafeAreaEdge.BOTTOM]) .backgroundColor(`rgba(70,130,180,${this.opacityNum >= 1 ? 1 : this.opacityNum})`) .position({ x: 0, y: 0 }) .height(66 + this.safeTopHeight) .zIndex(99); Column() { this.listControllerBuilder(); } .translate({ y: -(this.safeTopHeight + 5) }) .width('100%') .backgroundColor('#F1F3F5') .height(`calc(100% + ${this.safeTopHeight + 5}vp)`); } .width('100%') .height('100%'); } @Builder listControllerBuilder() { List({ space: 20, initialIndex: 0 }) { ListItem() { Image($r('app.media.mountain')) // 此处'mountain'仅作示例,请开发者自行替换。 .height(300) .width('100%'); }; ForEach(this.arr, (item: number) => { ListItem() { Text('' + item) .margin({ left: '5%' }) .width('90%') .height(100) .fontSize(16) .textAlign(TextAlign.Center) .borderRadius(10) .backgroundColor(0xFFFFFF); } .align(Alignment.Center); }, (item: string) => item); } .onReachStart(() => { this.opacityNum = 0; }) .onWillScroll((scrollOffset: number) => { this.scrollSum += scrollOffset; this.opacityNum = this.scrollSum / 200; }) .listDirection(Axis.Vertical) // 排列方向 .scrollBar(BarState.Off) .friction(0.6) .chainAnimation(false) .edgeEffect(EdgeEffect.Spring) // 配合EdgeEffect.Spring可以触发list回弹效果 .nestedScroll({ scrollForward: NestedScrollMode.PARENT_FIRST, scrollBackward: NestedScrollMode.SELF_FIRST }) .width('100%'); } }