如何在JavaScript模态窗口上设置焦点?

10
我们的网站涉及一些制作覆盖式模态窗口的JavaScript。
然而,这里存在一个较大的无障碍问题,即一旦触发了模态窗口,焦点仍然停留在触发元素上,而不是在模态窗口本身上。
这些模态窗口可以包含各种HTML元素,如标题、段落和表单控件。我想让焦点从模态窗口内的第一个元素开始,通常会是 h4 标签。
我已经尝试使用 focus() 函数,但它不能与多个 HTML 元素一起使用。
有一种想法是在窗口中添加一个空的 a 标签,以获得焦点,但我对这种方法不确定。
4个回答

11

虽然晚来一步,但现有的答案并没有考虑无障碍性。

关于可访问模态框的W3C维基页面提供了比OP要求更多的见解,其中相关部分是在模态框容器上设置tabindex=-1(它还应该有一个aria-dialog属性),以便它可以获得:focus

这是设置模态框焦点最具可访问性的方式,还有更多关于将焦点保持在模态框内部并将其返回到触发模态框的元素的文档 - 这里需要解释的内容相当多,因此我建议任何感兴趣的人都检查上面的链接。


1

0

您可以将文本框附加到模态HTML的开头,设置焦点,然后隐藏文本框。据我理解,这应该符合您的需求。


1
这是一种方法,但我更喜欢不在代码中添加空文本框,因为这样可以提高可访问性和代码的整洁程度。 - user502014
@user502014 文本框不会显示,因此无障碍性不应成为问题。如果您发现更清晰的代码,请随意使用它,但请记住您需要准备“备选方案”。 - Shadow The Spring Wizard

0
为了在模态框中限制焦点,我使用了这种方法。因此,其基本思想就是将焦点限制在模态框的HTML元素内,不允许其跑出模态框之外。
  // 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();

你可以在这里找到它 将焦点限制在模态框内


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接