因此,出于可访问性的目的,我试图捕获选项卡focus
和blur
事件,以捕获模态内的选项卡顺序。
由于某些原因,我遇到了一些奇怪的浏览器行为。
在我的组件中有以下代码:
// On Init
ngOnInit (){
// Get all of the buttons and anchors in the modal
var buttons = this.modal.nativeElement.querySelectorAll("button, a");
// Get the number of buttons
var numButtons = buttons.length;
// Get the last button
var lastButton = buttons[numButtons - 1];
// When the last button loses focus
lastButton.addEventListener("blur", (e: any) => {
// Prevent Default
e.preventDefault();
// Focus on the modals close button
this.focusCloseButton();
})
}
从技术上讲,这是完美的。如果我在调用this.focusCloseButton
后注销活动元素,我确实得到了关闭按钮的引用。
然而,标签实际上移动到浏览器本身的第一个元素。对于Chrome浏览器,这是"查看网站信息"按钮在URL栏的左侧。在Firefox中,这是选项卡列表中的第一个选项卡。
我怎样才能正确地捕获这个,使浏览器不劫持tab键?
显然,blur
事件发生得太晚,无法在浏览器接管之前捕获。
相反,我使用键绑定来检测何时按下tab键并从那里进行捕获。
// The OnInit function handles capturing tab order
ngOnInit (){
// All of the buttons and links in the modal
var buttons = this.modal.nativeElement.querySelectorAll("button, a");
// The first button or link in the modal
var firstButton = buttons[0];
// The last button or link in the modal
var lastButton = buttons[buttons.length - 1];
// Listen for keydown events on the modal
this.modal.nativeElement.addEventListener("keydown", (e: any)=> {
// If the key pressed was the tab button
if ( e.keyCode === 9 && !e.shiftKey ) {
// If the currently active element is the last button
if (document.activeElement == lastButton){
// Prevent default action
e.preventDefault();
// Put focus on the close button
this.focusCloseButton();
}
} else if ( e.keyCode === 9 && e.shiftKey === true ){
// If the key pressed was shift+tab
// And the currently active button is the close button
if ( document.activeElement == firstButton ){
// Prevent Default
e.preventDefault();
// Focus the last button
lastButton.focus();
}
}
})
}
为那些想知道这是什么。focusCloseButton:
// Puts focus on the close button
focusCloseButton: Function = function(){
this.closeButton.nativeElement.focus();
};
对closeButton的引用是由ViewChild创建的:
// Reference to the close button
@ViewChild("closeButton") closeButton: ElementRef;
与被标记的元素绑定到dom:
<button #closeButton></button>