使用tabindex='-1' 和其他HTML 更改 尝试了不同的解决方案,但在我的情况下没有任何效果,所以这里有一些在我的情况下有效的方法。
第 1 步: 在对话框组件上添加 keydown 事件
@HostListener('document:keydown', ['$event'])
handleTabKeyWInModel(event: any) {
this.sharedService.handleTabKeyWInModel(event, '#modal_id', this.elementRef.nativeElement, 'input,button,select,textarea,a,[tabindex]:not([tabindex="-1"])');
}
这将过滤在模态对话框中预先存在的元素。
第 2 步:在共享服务中处理焦点添加常用方法(或者您也可以将其添加到您的组件中)
handleTabKeyWInModel(e, modelId: string, nativeElement, tagsList: string) {
if (e.keyCode === 9) {
const focusable = nativeElement.querySelector(modelId).querySelectorAll(tagsList);
if (focusable.length) {
const first = focusable[0];
const last = focusable[focusable.length - 1];
const shift = e.shiftKey;
if (shift) {
if (e.target === first) { // shift-tab pressed on first input in dialog
last.focus();
e.preventDefault();
}
} else {
if (e.target === last) { // tab pressed on last input in dialog
first.focus();
e.preventDefault();
}
}
}
}
}
现在此方法将采用模态对话框原生元素并开始评估每个 tab 键。最后,我们将过滤第一个和最后一个事件,以便我们可以专注于适当的元素(在最后一个元素选项卡点击之后的第一个和第一个元素上的最后一个 shift+tab 事件)。
编码愉快.. :)