- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在使用 Angular
开发应用程序和 Semantic-UI
.该应用程序应该是可访问的,这意味着它应该符合 WCAG 2.0。
为了达到这个目的,模态应该将焦点保持在对话框内,并防止用户走出去或在位于模态下的页面元素之间使用“标签”移动。
我找到了一些工作示例,如下所示:
dialog
HTML 5.1 元素:https://demo.agektmr.com/dialog role="dialog"
aria-labelledby="modal-title"
aria-modal="true"
最佳答案
目前没有简单的方法来实现这一目标。 inert attribute建议尝试通过使具有该属性的任何元素及其所有子元素都无法访问来解决此问题。然而,采用速度缓慢,直到最近才采用 land in Chrome Canary behind a flag .
另一个建议的解决方案是 making a native API that would keep track of the modal stack ,基本上使当前不是堆栈顶部的所有内容都处于惰性状态。我不确定提案的状态,但看起来不会很快实现。
那么,这让我们何去何从?
不幸的是没有一个好的解决方案。一种流行的解决方案是 create a query selector of all known focusable elements然后通过将 keydown 事件添加到模态中的最后一个和第一个元素来将焦点捕获到模态。但是,随着web组件和shadow DOM的兴起,这个解决方案可以no longer find all focusable elements .
如果您始终控制对话框中的所有元素(并且您没有创建通用对话框库),那么最简单的方法可能是在第一个和最后一个可聚焦元素上为 keydown 添加事件监听器,检查 tab 或使用 shift tab ,然后聚焦第一个或最后一个元素以捕获焦点。
如果你正在创建一个通用的对话框库,我发现唯一有效的方法就是使用惰性 polyfill 或者让模态之外的所有东西都有一个 tabindex=-1
.
var nonModalNodes;
function openDialog() {
var modalNodes = Array.from( document.querySelectorAll('dialog *') );
// by only finding elements that do not have tabindex="-1" we ensure we don't
// corrupt the previous state of the element if a modal was already open
nonModalNodes = document.querySelectorAll('body *:not(dialog):not([tabindex="-1"])');
for (var i = 0; i < nonModalNodes.length; i++) {
var node = nonModalNodes[i];
if (!modalNodes.includes(node)) {
// save the previous tabindex state so we can restore it on close
node._prevTabindex = node.getAttribute('tabindex');
node.setAttribute('tabindex', -1);
// tabindex=-1 does not prevent the mouse from focusing the node (which
// would show a focus outline around the element). prevent this by disabling
// outline styles while the modal is open
// @see https://www.sitepoint.com/when-do-elements-take-the-focus/
node.style.outline = 'none';
}
}
}
function closeDialog() {
// close the modal and restore tabindex
if (this.type === 'modal') {
document.body.style.overflow = null;
// restore or remove tabindex from nodes
for (var i = 0; i < nonModalNodes.length; i++) {
var node = nonModalNodes[i];
if (node._prevTabindex) {
node.setAttribute('tabindex', node._prevTabindex);
node._prevTabindex = null;
}
else {
node.removeAttribute('tabindex');
}
node.style.outline = null;
}
}
}
关于modal-dialog - 如何在模态对话框中保持焦点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44452084/
我是一名优秀的程序员,十分优秀!