我有一个移动菜单,单击打开菜单按钮时会打开该菜单。我正在尝试在菜单打开时向菜单添加陷阱焦点功能,以便用户在按 Tab 键时无法使用键盘访问菜单之外的内容。
我使用事件监听器来监听菜单中的 Tab 和Shift Tab 键按下事件。逻辑是,如果事件元素没有只有我的菜单项具有的类,则将焦点锁定回菜单的关闭按钮。
问题是焦点立即卡在我的关闭按钮上,我无法移动它(即使它具有“in-listview”类)。我意识到我的代码可能不是实现此功能的最佳方式,但现在我只想知道为什么我的类似乎没有被识别,我可以在之后进行整理。我的应用程序是使用 ReactJS 构建的。
openNav = () => {
const listView = document.querySelector(".listview");
listView.classList.remove('closeMobMenu');
listView.style.visibility = "visible";
listView.classList.add('openMobMenu');
document.addEventListener('keydown', this.trapTabMobMenu)//Maybe move this to componentDidMount()?
}
trapTabMobMenu = (event) => {
if(event.keyCode === 9) { // if the tab key is pressed in the mobile menu
const closeBtn = this.closeBtn;
let activeElement = document.activeElement;
if(event.shiftKey) { // shift-tab
event.preventDefault();
//if focused element does not have class in-list-view
if(!activeElement.classList.contains("in-listview")) {
closeBtn.focus();
}
} else { // normal tab
event.preventDefault();
if(!activeElement.classList.contains("in-listview")) {
closeBtn.focus();
}
}
}
if(event.keyCode === 27) {
this.closeNav();
}
}
<button ref={(close) => { this.closeBtn = close; }} className="closebtn in-listview" onClick={closeNav} onKeyPress={handleKeyPress} tabIndex="2">×</button>
最佳答案
document.activeElement
直到焦点事件完成后才会设置,因此上面的代码不会对触发 onFocus
的新元素执行逻辑事件。
您需要将 document.activeElement
更改为 event.target
,然后执行您的逻辑。
https://developer.mozilla.org/en-US/docs/Web/API/DocumentOrShadowRoot/activeElement
关于javascript - 事件监听器似乎无法识别我的类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51527782/