是否可以使用键盘导航到使用 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>
答案 0 :(得分:11)
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了解演示。
答案 1 :(得分:1)
很好的例子。
但是,你为什么设置setTimeout
?
一些具体原因?
setTimeout(function(){
$(".search-option:first").focus();
},100);
我做了同样的例子,模拟了一个输入选择框,没有超时。 Check this out