Element: ariaOwnsElements 属性
Element
接口的 ariaOwnsElements
属性是一个数组,其中包含定义应用到父元素及其子元素之间的视觉、功能或上下文关系的元素。当 DOM 层级结构无法用于表示这种关系,并且辅助技术无法直接获取时,就会使用此属性。
aria-owns
主题包含了关于属性和属性如何使用的更多信息。
值
HTMLElement
的子类数组。
读取时,返回的数组是静态的且只读的。写入时,将复制分配的数组:之后对数组的更改不会影响属性的值。
描述
此属性是使用 aria-owns
属性来指示元素所有权的一种灵活的替代方案。与 aria-owns
不同,分配给此属性的元素不必具有 id
属性。
当定义了 aria-owns
属性时,此属性会反映该属性的值,但仅限于匹配有效作用域内元素的已列出的引用 id
值。如果设置了此属性,则相应的属性会被清除。有关反映的元素引用和作用域的更多信息,请参阅反映的属性指南中的 反映的元素引用。
示例
获取被拥有的元素
此示例演示了 aria-owns
属性和属性的用法。
该代码在单独且非嵌套的 <div>
元素中定义了一个菜单及其关联的子菜单。由于这些元素没有嵌套,DOM 无法捕捉菜单和子菜单之间的所有权关系。在这里,我们通过 aria-owns
属性将此信息提供给可访问性工具,但也可以通过反映的属性来实现。
请注意,我们可以构建一个子菜单嵌套在其中的菜单:该示例是为了方便演示需要定义关系的场景而刻意设计的。
HTML
HTML 定义了菜单的 <div>
元素,其中 id=parentMenu
,子菜单的 id="subMenu1"
。我们在中间添加了一个 <div>
,以便更清楚地表明 DOM 中没有定义直接的所有权模型。
父菜单 <div>
包含属性 aria-owns="subMenu1"
来创建此所有权关系。
<div class="menu" id="parentMenu" role="menubar" aria-owns="subMenu1">
Top level menu (hover over)
</div>
<div>Some other element</div>
<div class="submenu" id="subMenu1" role="menu">
<a href="#" role="menuitem">Menu item 1</a>
<a href="#" role="menuitem">Menu item 2</a>
<a href="#" role="menuitem">Menu item 3</a>
</div>
CSS
CSS 为菜单和子菜单设置样式,并在鼠标悬停在菜单上时显示子菜单。
.menu {
position: relative;
display: inline-block;
color: purple;
}
.submenu {
display: none;
position: absolute;
background-color: #f9f9f9;
min-width: 160px;
box-shadow: 0px 6px 14px 0px rgb(0 0 0 / 0.2);
z-index: 1;
top: 20px;
left: 0;
}
.menu:hover ~ .submenu {
display: block;
}
.submenu a {
color: black;
padding: 12px 16px;
text-decoration: none;
display: block;
}
.submenu a:hover {
background-color: #f1f1f1;
}
JavaScript
代码首先检查 ariaOwnsElements
是否受支持。如果受支持,我们将记录该属性、属性中的元素以及每个元素的 id
值。
// Feature test for ariaOwnsElements
if ("ariaOwnsElements" in Element.prototype) {
const parentMenu = document.querySelector("#parentMenu");
log(`parentMenu.getAttribute(): ${parentMenu.getAttribute("aria-owns")}`);
log(`parentMenu.ariaOwnsElements: ${parentMenu.ariaOwnsElements}`);
parentMenu.ariaOwnsElements?.forEach((elem) => {
log(` id: ${elem.id}`);
});
} else {
log("element.ariaOwnsElements: not supported by browser");
}
结果
运行代码的结果如下所示。日志显示,使用 aria-owns
属性定义的关系已反映在 ariaOwnsElements
属性中(数组中的元素与属性元素引用匹配)。
规范
规范 |
---|
无障碍富互联网应用程序 (WAI-ARIA) # dom-ariamixin-ariaownselements |
浏览器兼容性
加载中…
另见
aria-owns
属性ElementInternals.ariaOwnsElements
- Attribute reflection 指南中的Reflected element references。