twitter-bootstrap 在 Bootstrap 下拉菜单中启用键盘导航
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17713520/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Enabling keyboard navigation in the Bootstrap dropdown-menu
提问by JavaSheriff
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?
是否可以使用键盘导航到下拉菜单Tab,并使用箭头键导航到下拉菜单的子元素?
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>
采纳答案by rybo111
Update
更新
Bootstrap now supports up/down keys as standard.
Bootstrap 现在支持向上/向下键作为标准。
So if you want Tabto activate the dropdown, just get the key code(9) and do the following:
因此,如果您想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();
}
});
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;
}
});
See this JSFiddlefor a demo.
有关演示,请参阅此 JSFiddle。
回答by nneeggrroo
Nice example.
很好的例子。
But, Why did you set a setTimeout?
Some specific reason?
但是,你为什么设置一个setTimeout?有什么具体原因?
setTimeout(function(){
$(".search-option:first").focus();
},100);
I made the same example, simulating an input select box, without a timeout. Check this out.
我做了同样的例子,模拟输入选择框,没有超时。看看这个。

