是否可以使用键盘使用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>


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

最佳答案

更新资料

Bootstrap现在标准支持上/下键。

因此,如果您希望Tab激活下拉菜单,只需get the key code(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();
    }
});


而且,如果您要为用户专注于下拉菜单项添加更多功能,请执行以下操作:

$('.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;
    }
});


有关演示,请参见this JSFiddle

关于twitter-bootstrap - 在Bootstrap下拉菜单中启用键盘导航,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17713520/

10-16 19:38