如何使选项卡索引适用于下拉菜单?

How to make tab index work for dropdowns?

我有一个带有 bootstrap 下拉组件的 header,我正在尝试使用 tabindex 启用对该元素的键盘导航。下面是html和简单的css:

HTML:
<span class="pull-right">
   <span class="help-menu dropdown">
       <span class="dropdown-toggle" data-toggle="dropdown" role="button">
          <span class="help-header" tab-index="0">Help</span>
        </span>
           <ul class="dropdown-menu pull-right" tabindex="-1" role="menu">
             <li tabindex="-1"><a [href]="/help.html" target="_blank">Docs</a></li>
           </ul>
    </span>
 </span>

CSS:

.help-header{
   &:after{
      content: "BE"; //caret should be displayed!
   }
}
.help-menu{
     display: inline-block;
     cursor: pointer;
     background: aqua;
     margin-top: 10px;
    margin-right: 20px;
}

这里是Fiddlelink

现在,当我使用选项卡时,帮助不会获得焦点。但是,当我从 help-header class 中删除 tabindex 并将其应用于 class pull-right 的范围或 class help-menu 的范围和下拉菜单中,帮助文本获得选项卡上的焦点。尽管这得到了关注,但我看不到点击 enter 或 space 或向下箭头时的下拉菜单。

我真的不知道该怎么做。一段时间以来我一直在努力弄清楚,但我失败了。

我是不是漏掉了 tabindex 的任何核心概念。谁能帮助我或指出正确的方向。

非常感谢。

干杯。

The tabindex attribute explicitly defines the navigation order for focusable elements (typically links and form controls) within a page. It can also be used to define whether elements should be focusable or not.

[Both] tabindex="0" and tabindex="-1" have special meaning and provide distinct functionality in HTML. A value of 0 indicates that the element should be placed in the default navigation order. This allows elements that are not natively focusable (such as <div>, <span>, and <p>) to receive keyboard focus. Of course one should generally use links and form controls for all interactive elements, but this does allow other elements to be focusable and trigger interaction.

A tabindex="-1" value removes the element from the default navigation flow (i.e., a user cannot tab to it), but it allows it to receive programmatic focus, meaning focus can be set to it from a link or with scripting.** This can be very useful for elements that should not be tabbed to, but that may need to have focus set to them.

A good example is a modal dialog window - when opened, focus should be set to the dialog so a screen reader will begin reading and the keyboard will begin navigating within the dialog. Because the dialog (probably just a <div> element) is not focusable by default, assigning it tabindex="-1" allows focus to be set to it with scripting when it is presented.

A value of -1 can also be useful in complex widgets and menus that utilize arrow keys or other shortcut keys to ensure that only one element within the widget is navigable with the tab key, but still allow focus to be set on other components within the widget.

所以总而言之,如果你想通过键盘选项卡启用某些元素,你应该将值更改为 0.