[英]How to set the focus on a javascript modal window?
我們的網站涉及一些 javascript 產生覆蓋模式 windows。
但是,這有一個可訪問性問題,一旦模式被觸發, focus
仍然在觸發元素上,而不是模式本身。
這些模式可以包括各種 html 元素、標題、段落和表單控件。 我想要的是從模態中的第一個元素開始的焦點,因此很可能是 h4 標簽。
我已經探索過使用focus()
function 但這不適用於許多 html 元素。
一種想法是在 window 中添加一個空a
標簽,這樣可以獲得焦點,但我不確定這種方法。
派對很晚,但現有的答案並不尊重可訪問性。
可訪問模態的W3C wiki頁面提供了比OP中所要求的更多的洞察力,相關部分在模態容器上具有tabindex=-1
(它還應該具有aria-dialog
屬性),因此它可以得到:focus
。
這是將焦點設置在模態上最容易獲得的方法,還有更多關於將其保留在模態中的文檔 - 並將其返回到觸發模態的元素 - 這里要解釋的很多,所以我建議任何人有興趣檢查上面的鏈接。
您可以將文本框附加到模式HTML的開頭,設置焦點然后隱藏文本框。 如果我了解您的需求,應該具有預期的效果。
您可以嘗試模糊() 具有焦點的元素 。
將焦點捕獲在模態中我使用了這種方法。 所以它背后的基本思想就是將焦點捕獲在模態 HTML 元素中,並且不允許它超出模態 go 。
// add all the elements inside modal which you want to make focusable
const focusableElements =
'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])';
const modal = document.querySelector('#exampleModal'); // select the modal by it's id
const firstFocusableElement = modal.querySelectorAll(focusableElements)[0]; // get first element to be focused inside modal
const focusableContent = modal.querySelectorAll(focusableElements);
const lastFocusableElement = focusableContent[focusableContent.length - 1]; // get last element to be focused inside modal
document.addEventListener('keydown', function(e) {
let isTabPressed = e.key === 'Tab' || e.keyCode === 9;
if (!isTabPressed) {
return;
}
if (e.shiftKey) { // if shift key pressed for shift + tab combination
if (document.activeElement === firstFocusableElement) {
lastFocusableElement.focus(); // add focus for the last focusable element
e.preventDefault();
}
} else { // if tab key is pressed
if (document.activeElement === lastFocusableElement) { // if focused has reached to last focusable element then focus first focusable element after pressing tab
firstFocusableElement.focus(); // add focus for the first focusable element
e.preventDefault();
}
}
});
firstFocusableElement.focus();
你可以在這里找到它trap focus inside the modal
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.