首页 > 解决方案 > 专注陷阱

不是绝对的,焦点转义到浏览器 UI 元素

问题描述

我试图了解<dialog>html 元素和MDN 在这里列出的示例。

当我从中运行代码时...

var updateButton = document.getElementById('updateDetails');
var favDialog = document.getElementById('favDialog');
var outputBox = document.querySelector('output');
var selectEl = document.querySelector('select');
var confirmBtn = document.getElementById('confirmBtn');

// "Update details" button opens the <dialog> modally
updateButton.addEventListener('click', function onOpen() {
  if (typeof favDialog.showModal === "function") {
    favDialog.showModal();
  } else {
    alert("The <dialog> API is not supported by this browser");
  }
});
// "Favorite animal" input sets the value of the submit button
selectEl.addEventListener('change', function onSelect(e) {
  confirmBtn.value = selectEl.value;
});
// "Confirm" button of form triggers "close" on dialog because of [method="dialog"]
favDialog.addEventListener('close', function onClose() {
  outputBox.value = favDialog.returnValue + " button clicked - " + (new Date()).toString();
});
<!-- Simple pop-up dialog box containing a form -->
<dialog id="favDialog">
  <form method="dialog">
    <p><label>Favorite animal:
      <select>
        <option></option>
        <option>Brine shrimp</option>
        <option>Red panda</option>
        <option>Spider monkey</option>
      </select>
    </label></p>
    <menu>
      <button value="cancel">Cancel</button>
      <button id="confirmBtn" value="default">Confirm</button>
    </menu>
  </form>
</dialog>

<menu>
  <button id="updateDetails">Update details</button>
</menu>

<output aria-live="polite"></output>

...我发现当对话框打开时,焦点并没有像ARIA 模态示例描述的那样完全“陷阱”。他们说当用户按下 tab 键时:

当焦点位于对话框中的最后一个可聚焦元素上时,将焦点移至对话框中的第一个可聚焦元素。

然而,对话框元素的 MDN 示例允许用户“跳出”模式并进入浏览器框架。在我的情况下,使用 chrome,在确认按钮按下选项卡后,将聚焦“查看站点信息”按钮,然后是文档区域之外的地址栏。

这里发生了什么。MDN 的例子不完整吗?Web 开发人员是否需要编写额外的 JS 代码来真正聚焦陷阱才能<dialog>在生产中使用该元素?或者从可访问性的角度来看,允许模态部分捕获焦点是否“可以接受”,如示例中所示,其中选项卡上的按键可以暂时转义到浏览器 UI 元素。

标签: javascripthtmlmodal-dialogwai-aria

解决方案


我发现当对话框打开时,焦点并没有像ARIA 模态示例描述的那样完全“陷阱”。

那是因为 W3 指南上的示例确实有自定义 javascript来捕获对对话框的使用焦点。您可以看到评论中也提到了相同的内容:

...

// Bracket the dialog node with two invisible, focusable nodes.
// While this dialog is open, we use these to make sure that focus never
// leaves the document even if dialogNode is the first or last node.
var preDiv = document.createElement('div');
this.preNode = this.dialogNode.parentNode.insertBefore(preDiv, this.dialogNode);
this.preNode.tabIndex = 0;
var postDiv = document.createElement('div');
this.postNode = this.dialogNode.parentNode.insertBefore(postDiv, this.dialogNode.nextSibling);
this.postNode.tabIndex = 0;

...

这里发生了什么。MDN 的例子不完整吗?

我不会说它不完整,但是两个指南都针对不同的受众,您提到的 w3 文档是可访问性指南,而 MDN 文档只是dialogHTML 规范中描述的文档。

Web 开发人员是否需要编写额外的 JS 代码来真正聚焦陷阱才能在生产中使用该元素?或者从可访问性的角度来看,允许模态部分捕获焦点,如示例中的“可接受”,其中选项卡上的按键可以暂时转义到浏览器 UI 元素。

我想这取决于您和您的产品用户。大多数情况下,从可访问性的角度来看,建议将用户焦点捕获在对话框中,并允许通过退出键、关闭按钮和取消按钮来关闭对话框。

是的,您必须通过添加 2 个可聚焦元素在 javascript 或 HTML 中为鼠标捕获添加自定义代码,如您提到的可访问性指南页面上的示例中所示。


推荐阅读