在Bootstrap下拉菜单中启用键盘导航 [英] Enabling keyboard navigation in the Bootstrap dropdown-menu

查看:116
本文介绍了在Bootstrap下拉菜单中启用键盘导航的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is it possible to navigate using the keyboard to the drop down menu using Tab, and navigate using the arrow keys to the sub elements of the drop down?

这是我现在拥有的代码:

Here is the code I have now:

<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现在支持标准的向上/向下键。

Update

Bootstrap now supports up/down keys as standard.

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

So if you want Tab to activate the dropdown, just get the key code (9) and do the following:

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

如果您想为用户专注于下拉菜单项添加更多功能,

And if you want to add further functionality for when the user is focused on a dropdown menu item:

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

请参见此JSFiddle 进行演示。

这篇关于在Bootstrap下拉菜单中启用键盘导航的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆