1# 焦点事件 2 3焦点事件指页面焦点在可获焦组件间移动时触发的事件,组件可使用焦点事件来处理相关逻辑。 4 5> **说明:** 6> 7> - 从API Version 8开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 8> 9> - 目前仅支持通过外接键盘的tab键、方向键触发。不支持嵌套滚动组件场景按键走焦。 10> 11> - 存在默认交互逻辑的组件例如[Button](ts-basic-components-button.md)、[TextInput](ts-basic-components-textinput.md)等,默认即为可获焦,[Text](ts-basic-components-text.md)、[Image](ts-basic-components-image.md)等组件默认状态为不可获焦,不可获焦状态下,无法触发焦点事件,需要设置focusable属性为true才可触发。 12> 13> - 对于有获焦能力的容器组件,例如[Stack](ts-container-stack.md)、[Row](ts-container-row.md)等,若不存在可获焦子组件,该容器组件不可获焦。为其配置onClick或是单指单击的Tap手势,该组件会隐式地成为可获焦组件。 14> 15> - 焦点开发及组件获焦能力参考[焦点开发指南](../../../ui/arkts-common-events-focus-event.md)。 16 17## onFocus 18 19onFocus(event: () => void) 20 21当前组件获取焦点时触发的回调。 22 23**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 24 25**系统能力:** SystemCapability.ArkUI.ArkUI.Full 26 27## onBlur 28 29onBlur(event:() => void) 30 31当前组件失去焦点时触发的回调。 32 33**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 34 35**系统能力:** SystemCapability.ArkUI.ArkUI.Full 36 37 38## 示例 39 40该示例展示了组件获焦和失焦的情况,按钮获焦和失焦时会改变按钮的颜色。 41 42```ts 43// xxx.ets 44@Entry 45@Component 46struct FocusEventExample { 47 @State oneButtonColor: string = '#FFC0CB' 48 @State twoButtonColor: string = '#87CEFA' 49 @State threeButtonColor: string = '#90EE90' 50 51 build() { 52 Column({ space: 20 }) { 53 // 通过外接键盘的上下键可以让焦点在三个按钮间移动,按钮获焦时颜色变化,失焦时变回原背景色 54 Button('First Button') 55 .backgroundColor(this.oneButtonColor) 56 .width(260) 57 .height(70) 58 .fontColor(Color.Black) 59 .focusable(true) 60 .onFocus(() => { 61 this.oneButtonColor = '#FF0000' 62 }) 63 .onBlur(() => { 64 this.oneButtonColor = '#FFC0CB' 65 }) 66 Button('Second Button') 67 .backgroundColor(this.twoButtonColor) 68 .width(260) 69 .height(70) 70 .fontColor(Color.Black) 71 .focusable(true) 72 .onFocus(() => { 73 this.twoButtonColor = '#FF0000' 74 }) 75 .onBlur(() => { 76 this.twoButtonColor = '#87CEFA' 77 }) 78 Button('Third Button') 79 .backgroundColor(this.threeButtonColor) 80 .width(260) 81 .height(70) 82 .fontColor(Color.Black) 83 .focusable(true) 84 .onFocus(() => { 85 this.threeButtonColor = '#FF0000' 86 }) 87 .onBlur(() => { 88 this.threeButtonColor = '#90EE90' 89 }) 90 }.width('100%').margin({ top: 20 }) 91 } 92} 93``` 94 95 