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> - 焦点开发参考[焦点开发指南](../../../ui/arkts-common-events-focus-event.md) 14 15## onFocus 16 17onFocus(event: () => void) 18 19当前组件获取焦点时触发的回调。 20 21**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 22 23**系统能力:** SystemCapability.ArkUI.ArkUI.Full 24 25## onBlur 26 27onBlur(event:() => void) 28 29当前组件失去焦点时触发的回调。 30 31**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 32 33**系统能力:** SystemCapability.ArkUI.ArkUI.Full 34 35 36## 示例 37 38该示例展示了组件获焦和失焦的情况,按钮获焦和失焦时会改变按钮的颜色。 39 40```ts 41// xxx.ets 42@Entry 43@Component 44struct FocusEventExample { 45 @State oneButtonColor: string = '#FFC0CB' 46 @State twoButtonColor: string = '#87CEFA' 47 @State threeButtonColor: string = '#90EE90' 48 49 build() { 50 Column({ space: 20 }) { 51 // 通过外接键盘的上下键可以让焦点在三个按钮间移动,按钮获焦时颜色变化,失焦时变回原背景色 52 Button('First Button') 53 .backgroundColor(this.oneButtonColor) 54 .width(260) 55 .height(70) 56 .fontColor(Color.Black) 57 .focusable(true) 58 .onFocus(() => { 59 this.oneButtonColor = '#FF0000' 60 }) 61 .onBlur(() => { 62 this.oneButtonColor = '#FFC0CB' 63 }) 64 Button('Second Button') 65 .backgroundColor(this.twoButtonColor) 66 .width(260) 67 .height(70) 68 .fontColor(Color.Black) 69 .focusable(true) 70 .onFocus(() => { 71 this.twoButtonColor = '#FF0000' 72 }) 73 .onBlur(() => { 74 this.twoButtonColor = '#87CEFA' 75 }) 76 Button('Third Button') 77 .backgroundColor(this.threeButtonColor) 78 .width(260) 79 .height(70) 80 .fontColor(Color.Black) 81 .focusable(true) 82 .onFocus(() => { 83 this.threeButtonColor = '#FF0000' 84 }) 85 .onBlur(() => { 86 this.threeButtonColor = '#90EE90' 87 }) 88 }.width('100%').margin({ top: 20 }) 89 } 90} 91``` 92 93 