2013-07-18 30 views
8

是否可以使用鍵盤導航到使用Tab的下拉菜單,並使用箭頭鍵導航到下拉菜單的子元素?在Bootstrap下拉菜單中啓用鍵盤導航

這裏是我現在的代碼:

<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/

+0

我看到你編輯後,我回答。你有沒有看到我的答案? – rybo111

+1

最新評論,但...我認爲現在我們可以添加角色=「菜單」的ul.dropdown菜單和角色=「導航」到div.navbar(在引導2和3),似乎啓用鍵盤輔助功能非常好。但我認爲你的問題的HTML標記不遵循引導示例... – djKianoosh

回答

11

更新

引導現在支持上/下鍵爲標準。

所以,如果你想標籤激活下拉列表中,只是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進行演示。

+0

主頁/結束和信件導航丟失:-) – xamiro

+0

@ xamiro-dev查看更新的答案。您可以通過[查找鍵碼](http://keycode.info)並添加開關盒添加字母導航。 – rybo111

1

不錯的例子。

但是,爲什麼設置了setTimeout? 一些具體原因?

setTimeout(function(){ 
    $(".search-option:first").focus(); 
},100); 

我做了同樣的例子,模擬輸入選擇框,沒有超時。 Check this out

+0

這可能是當時瀏覽器的怪癖。 – rybo111

+1

@Emzor如果您有興趣,代碼現在已更新。 – rybo111

+1

@ rybo111非常感謝信息:-) – Emzor