问题描述
目标:当从一个页面导航到另一个页面时,NVDA 屏幕阅读器应该读取标题标签或主要地标
观察到的行为:导航时屏幕阅读器不会读取标题标签。 但是每当发生重新加载/刷新时,屏幕阅读器都会读取标题标签
<h1 tabindex="-1">
Some heading
</h1>
constructor(private router: Router) {
this.readMainLandMark();
}
readMainLandMark() {
// console.log(document.getElementsByTagName('h1')[0]); // Results undefined because of HTMLCollection is []
this.router.events.pipe(filter(e => e instanceof NavigationEnd)).subscribe(() => {
const mainHeaders = document.getElementsByTagName('h1');
if(mainHeaders.length !== 0) {
mainHeaders[0].focus();
}
});
}
Here NavigationEnd
识别前一个实例页面标题上下文。因此,在再次加载/刷新后,屏幕阅读器读取当前页面标题,将上一页视为当前页面,这就是为什么在重新加载相同页面标题后会读取标签的原因。但不是在导航时...
解决方法
<h1 id="main-content-header" tabindex="-1">
Some Heading Name
</h1>
readMainLandMark() {
this._router.events.pipe(filter(e => e instanceof NavigationEnd)).subscribe(() => {
const mainHeader = <HTMLElement>document.querySelector('#main-content-header');
if (mainHeader) {
(mainHeader as HTMLElement)?.focus();
}
});
}