首页 > 解决方案 > 当用户悬停我们正在显示按钮的 div 时,键盘访问不适用于带有按钮的内部 div。如何实现可访问性?

问题描述

我有带有两个按钮的 div 容器。当用户鼠标悬停或键盘焦点时,我正在显示该按钮。我无法通过键盘访问这些按钮。

下面是我的示例 HTML 和 CSS 代码。

<div class="ui-col ui-dropzone" tabindex="0">
    <div class="ui-edit-bar">
        <div class="label"></div>
        <button tabindex="0" data-action="edit">Edit Row</button>
        <button tabindex="0" data-action="edit">Edit Col</button>
    </div>
</div>

.ui-col:hover, .ui-col:focus {
  border: 1px dashed #17a2b8;
}

.ui-edit-bar {
  display: none;
  position: absolute;
  height: 30px;
  width: max-content;
  padding: 0 8px;
  color: #FFF;
  font-family: sans-serif;
  font-size: 11px;
  white-space: nowrap;
  z-index: 10000;
}

.ui-col:hover > .ui-edit-bar,  
.ui-col:focus > .ui-edit-bar {
  display: block;
}

在此处输入图像描述

能够使用键盘访问 div。但我无法通过键盘访问按钮。

标签: htmlcssaccessibility

解决方案


Your CSS is causing the problem.

You only display the edit bar when the <div class="ui-col ui-dropzone" tabindex="0"> is focused.

When you focus an item within that div it no longer has focus, so it reverts to display: none; and that then hides the <button>s from the accessibility tree.

You could use the :focus-within pseudo selector and make the parent opacity 0 but the support is not great for :focus-within yet.

.ui-col.ui-dropzone{
  opacity: 0;
}
.ui-col.ui-dropzone:hover,
.ui-col.ui-dropzone:focus-within{
  opacity: 1;
}
<div class="ui-col ui-dropzone">
    <div class="ui-edit-bar">
        <div class="label"></div>
        <button data-action="edit">Edit Row</button>
        <button data-action="edit">Edit Col</button>
    </div>
</div>

Realistically though (due to poor support for :focus-within) you would likely need a JavaScript fallback that changes the parent class when a button is focused and use that to control the opacity.

The advantage of this approach is that you are not having to add tabindex="0" everywhere so you code will be easier to maintain.


推荐阅读