Web组件调用loadUrl方法后,将focusable属性设置为false时就可以不自动获取焦点,通过onBlur和onFocus回调获取当前焦点状态。
import { webview } from '@kit.ArkWeb'; import { BusinessError } from '@kit.BasicServicesKit'; @Entry @Component struct Index { controller: webview.WebviewController = new webview.WebviewController(); @State webBorderColor: Color = Color.Yellow; @State isFocus: boolean = false; build() { Column() { Row({ space: 10 }) { Button('loadUrl调用按钮') .onClick(() => { try { this.controller.loadUrl('www.example.com'); this.isFocus = false; } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }); Button('获取焦点按钮') .onClick(() => { try { this.controller.requestFocus(); this.isFocus = true; } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }); }.padding({ top: 20, bottom: 20 }); Web({ src: 'www.example.com', controller: this.controller }) // 监听获焦事件,获焦后改变颜色 .onFocus(() => { this.webBorderColor = Color.Red; }) // 监听失焦事件,失焦后改变颜色 .onBlur(() => { this.webBorderColor = Color.Yellow; }) .fileAccess(false) .geolocationAccess(false) .margin(3) .borderWidth(10) .borderColor(this.webBorderColor) .focusable(this.isFocus) .height('45%'); }; } }