Bootstrap模态框无障碍问题:Lighthouse提示无可用名称
解决NgbModal无障碍访问性问题(Lighthouse报错:dialog元素无可用名称)
问题根源
你设置了ariaLabelledBy和ariaDescribedBy,但模态框内容模板中缺少对应ID的元素,或元素无有效文本,导致屏幕阅读器无法识别dialog的可访问名称,触发Lighthouse报错。
解决方案
1. 关联模板中存在的标题/描述元素ID
在ModalContentComponent的模板里,添加带有对应ID的标题和描述文本元素,确保ariaLabelledBy和ariaDescribedBy指向的ID真实存在且包含内容:
<div class="modal-header"> <!-- 标题元素ID匹配ariaLabelledBy设置的'uuuuu' --> <h5 class="modal-title" id="uuuuu">确认操作</h5> </div> <div class="modal-body" id="tttt"> <!-- 描述元素ID匹配ariaDescribedBy设置的'tttt' --> 请确认是否执行此操作,操作后无法撤销。 </div> <div class="modal-footer"> <button class="btn btn-secondary" (click)="closeModal.emit()">取消</button> <button class="btn btn-primary">确认</button> </div>
2. 直接设置ariaLabel(替代ID关联)
如果不需要关联模板元素,可直接通过ariaLabel参数给dialog设置可访问名称,无需依赖模板ID:
let m = this.modalService.open(ModalContentComponent, { backdrop: 'static', keyboard: false, ariaLabel: '确认操作模态框' // 直接设置可访问名称 }); m.componentInstance.closeModal.subscribe(($event: any) => m.close('Close click'))
3. 验证渲染结果
打开浏览器开发者工具,定位到dialog角色的元素(通常是.ngb-modal-content内部的div),检查是否存在以下属性:
aria-labelledby="uuuuu"(或aria-label="确认操作模态框")- 对应ID的元素存在且包含可见文本
4. 自动打开模态框的焦点优化(额外无障碍提升)
模态框自动打开时,确保焦点移到模态框内的可交互元素(如关闭按钮),避免焦点停留在背景页面:
在ModalContentComponent中添加焦点管理逻辑:
import { Component, EventEmitter, Output, AfterViewInit, ElementRef, ViewChild } from '@angular/core'; @Component({ selector: 'app-modal-content', templateUrl: './modal-content.component.html' }) export class ModalContentComponent implements AfterViewInit { @Output() closeModal = new EventEmitter(); @ViewChild('closeBtn') closeBtn!: ElementRef; ngAfterViewInit() { // 模态框加载后将焦点移到关闭按钮 this.closeBtn.nativeElement.focus(); } }
模板中给关闭按钮添加模板引用:
<button #closeBtn class="btn btn-secondary" (click)="closeModal.emit()">取消</button>
内容的提问来源于stack exchange,提问作者Avishag Saban
相关产品推荐
相关产品推荐

