如何用JavaScript检测元素的键盘导航焦点状态
解决思路及代码修改
核心问题分析
原生<th>元素默认不支持键盘聚焦,所以你用document.activeElement判断时,键盘Tab导航根本不会让它成为活跃元素,只有点击时可能因为PrimeNG组件的交互间接触发焦点,才会返回true。
具体解决步骤
- 让
<th>支持键盘聚焦:给元素添加tabindex="0",这样它就能被键盘Tab键正常导航聚焦。 - 用事件监听替代函数轮询:Angular中模板绑定函数会频繁执行且实时性差,应该通过
focus/blur事件实时跟踪焦点状态,再绑定到tooltipEvent。
修改后的代码
模板部分
<th id="myID" *ngSwitchCase="'validation'" [tooltipEvent]="tooltipEvent" pTooltip="I am a tooltip" tooltipPosition="top" [escape]="false" [pSortableColumn]="column.field" [ngStyle]="column.style" tabindex="0" (focus)="onThFocus()" (blur)="onThBlur()"> <div class="col-title"> <span data-testid="column-validationl-header" class="ui-column-title" >Validation </span> <p-sortIcon [field]="column.field" *ngIf="column.sortable"></p-sortIcon> </div> </th>
组件类部分
tooltipEvent: string = ''; // 聚焦时设置tooltipEvent onThFocus() { this.tooltipEvent = 'focus'; } // 失焦时清空 onThBlur() { this.tooltipEvent = ''; }
进阶:区分键盘/点击触发的焦点
如果需要严格只响应键盘导航的焦点,可添加全局按键监听来区分:
tooltipEvent: string = ''; private isKeyboardTriggered = false; // 监听Tab键按下,标记为键盘触发 @HostListener('document:keydown.tab') onTabPress() { this.isKeyboardTriggered = true; } // 监听鼠标按下,标记为鼠标触发 @HostListener('document:mousedown') onMousePress() { this.isKeyboardTriggered = false; } onThFocus() { // 仅当键盘触发时设置tooltipEvent this.tooltipEvent = this.isKeyboardTriggered ? 'focus' : ''; } onThBlur() { this.tooltipEvent = ''; }
内容的提问来源于stack exchange,提问作者opti13403
相关产品推荐
相关产品推荐

