在Bootstrap下拉菜单中启用键盘导航

use*_*026 14 accessibility keyboard-navigation twitter-bootstrap

是否可以使用键盘导航到下拉菜单Tab,并使用箭头键导航到下拉菜单的子元素?

这是我现在的代码:

<input type="text" value="click tab to jump to the drop down."/>
<div class="bs-docs-example">
    <div class="dropdown clearfix">
      <ul class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu" style="display: block; position: static; margin-bottom: 5px; *width: 180px;">
        <li><a tabindex="-1" href="#">Menu Item A</a></li>
        <li><a tabindex="-1" href="#">Menu Item B</a></li>
        <li><a tabindex="-1" href="#">Menu Item C</a></li>
        <li class="divider"></li>
        <li><a tabindex="-1" href="#">Menu Item A1</a></li>
            <li class="dropdown-submenu">
                <a tabindex="-1" href="#">Menu Item B1</a>
                <ul class="dropdown-menu">
                    <li><a tabindex="-1" href="#">You should navigate here with the keyboard.</a></li>
                    <li><a tabindex="-1" href="#">Thanks For your Help!</a></li>
                </ul>
            </li>
      </ul>
    </div>
</div>
Run Code Online (Sandbox Code Playgroud)

http://jsfiddle.net/MGwVM/1/

ryb*_*111 13

更新

Bootstrap现在支持上/下键作为标准.

因此,如果要Tab激活下拉列表,只需获取密钥代码(9)并执行以下操作:

$('.input-group input').keydown(function(e){
    if(e.which == 9){ // tab
        e.preventDefault();
        $(this).parent().find('.dropdown-toggle').click();
        $(this).parent().find('.dropdown-menu a:first').focus();
    }
});
Run Code Online (Sandbox Code Playgroud)

如果您想在用户关注下拉菜单项时添加更多功能:

$('.dropdown-menu a').keydown(function(e){
    switch(e.which){
        case 36: // home
            e.preventDefault();
            $(this).closest('.dropdown-menu').find('a:first').focus();
            break;
        case 35: // end
            e.preventDefault();
            $(this).closest('.dropdown-menu').find('a:last').focus();
            break;
    }
});
Run Code Online (Sandbox Code Playgroud)

请参阅此JSFiddle以获取演示.