> 文档中心 > HarmonyOS/OpenHarmony应用开发-ArkTS组件可见区域变化事件

HarmonyOS/OpenHarmony应用开发-ArkTS组件可见区域变化事件

一、事件
组件可见区域变化事件是组件在屏幕中的显示区域面积变化时触发的事件,提供了判断组件是否完全或部分显示在屏幕中的能力,适用于广告曝光埋点之类的场景。(api9开始支持)

二、示例

代码:

 

@Entry@Componentstruct Index {  scroller: Scroller = new Scroller()  private arr: number[] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]  @State testTextStr: string = 'test'  @State testRowStr: string = 'test'  build() {    Column() {      Column() { Text(this.testTextStr)   .fontSize(20)   .fontColor(Color.White)   .margin(10) Text(this.testRowStr)   .fontSize(20)   .fontColor(Color.White)      }      .width('100%')      .height(100)      .backgroundColor(Color.Black)      Scroll(this.scroller) { Column() {   Text("测试文本可见变化")     .fontSize(20)     .height(200)     .width(300)     .textAlign(TextAlign.Center)     .margin({ top: 50, bottom: 20 })     .backgroundColor(Color.Green)// 通过设置ratios为[0.0, 1.0],实现当组件完全显示或完全消失在屏幕中时触发回调     .onVisibleAreaChange([0.0, 1.0], (isVisible: boolean, currentRatio: number) => {console.info('Test Text isVisible: ' + isVisible + ', currentRatio:' + currentRatio)if (isVisible && currentRatio >= 1.0) {  console.info('Test Text is fully visible. currentRatio:' + currentRatio)  this.testTextStr = '测试文本是可见的'}if (!isVisible && currentRatio  {     console.info('Test Row isVisible:' + isVisible + ', currentRatio:' + currentRatio)     if (isVisible && currentRatio >= 1.0) {console.info('Test Row is fully visible.')this.testRowStr = '测试组件Row是可见的'     }     if (!isVisible && currentRatio  {     Text(item.toString()).width('90%').height(150).backgroundColor(0xFFFFFF).borderRadius(15).fontSize(16).textAlign(TextAlign.Center).margin({ top: 10 })   }, item => item) }.width('100%')      }      .backgroundColor(0x317aff)      .scrollable(ScrollDirection.Vertical)      .scrollBar(BarState.On)      .scrollBarColor(Color.Gray)      .scrollBarWidth(30)      .onScroll((xOffset: number, yOffset: number) => { console.info(xOffset + ' ' + yOffset)      })      .onScrollEdge((side: Edge) => { console.info('To the edge')      })      .onScrollEnd(() => { console.info('Scroll Stop')      })    }.width('100%').height('100%').backgroundColor(0xDCDCDC)  }}

完整代码地址:HarmonyOSAPP开发相关组件: 深圳市蛟龙腾飞网络科技有限公司 - Gitee.com