中国优质的IT技术网站
专业IT技术创作平台
IT职业在线教育平台
微信扫码分享
import { componentUtils, curves, display } from '@kit.ArkUI'; @Entry @Component struct ScrollSecondButton { @State indicatorIndex: number = 0 @State displayInfo: display.Display | null = null private scroller: Scroller = new Scroller() private arr: string[] = ['全部内容', '体检', '老年体检', '中年体检', '视频', '老年体检', '新歌', '入职体检', '新片'] aboutToAppear(): void { this.displayInfo = display.getDefaultDisplaySync(); //获取屏幕实例 } // 获取组件大小、位置、平移缩放旋转及仿射矩阵属性信息。 private getTextInfo(index: number): Record<string, number> { let modePosition: componentUtils.ComponentInfo = this.getUIContext().getComponentUtils().getRectangleById(index.toString()); try { return { 'left': px2vp(modePosition.windowOffset.x), 'width': px2vp(modePosition.size.width) } } catch (error) { return { 'left': 0, 'width': 0 } } } private scrollIntoView(currentIndex: number): void { const currentOffsetX: number = this.scroller.currentOffset().xOffset //当前滚动的偏移量 // 获取currentIndex 前两个按钮宽度 if (currentIndex >= 1) { const PreviousOne = this.getTextInfo(currentIndex - 1) // 将按钮滚动到第二个按钮 this.scroller.scrollTo({ xOffset: currentOffsetX + PreviousOne.left, yOffset: 0, animation: { duration: 300, curve: curves.interpolatingSpring(7, 1, 328, 34) // 动画曲线 } }) } else { this.scroller.scrollTo({ xOffset: 0, yOffset: 0 }) } } build() { Column() { Scroll(this.scroller) { Row() { ForEach(this.arr, (item: string, index: number) => { Column() { Text(item) .fontSize(16) .borderRadius(5) .fontColor(this.indicatorIndex === index ? "#3ca4dc" : Color.Black) .fontWeight(FontWeight.Normal) .onClick(() => { this.indicatorIndex = index this.scrollIntoView(index) }) } .padding({ left: 12, right: 12, top: 8, bottom: 8 }) .margin({ left: 5, right: 5 }) .borderRadius(20) .id(index.toString()) .backgroundColor(this.indicatorIndex === index ? "#f1f9fe" : "#f7f7f7") .border({ width: 1, color: this.indicatorIndex === index ? "#3ca4dc" : "#f7f7f7" }) }, (item: string) => item) } } .width('100%') .height('100%') .scrollable(ScrollDirection.Horizontal) .scrollBar(BarState.Off) .edgeEffect(EdgeEffect.None) } } }