2017-05-18 76 views
1

如何通過鍵盤選擇bootstrap4下拉菜單?如何通過鍵盤選擇bootstrap4下拉菜單?

<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js"></script> 
 
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js"></script> 
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js"></script> 
 
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet"/> 
 

 
<div class="dropdown show"> 
 
    <a class="btn btn-secondary dropdown-toggle" href="https://example.com" id="dropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> 
 
    Dropdown link 
 
    </a> 
 

 
    <div class="dropdown-menu" role="menu" aria-labelledby="dropdownMenuLink"> 
 
    <a class="dropdown-item" href="#">Action</a> 
 
    <a class="dropdown-item" href="#">Another action</a> 
 
    <a class="dropdown-item" href="#">Something else here</a> 
 
</div>

+0

代碼,請提供你已經嘗試過 –

回答

1

隨着tabindex="0"您現在可以使用鍵tab然後鍵space打開下拉列表,並使用tab通過列表項中導航。

此外,源參考的順序是不正確的,檢查以下

$(document).ready(function() { 
 
    $('.dropdown').keydown(function(e) { 
 
    switch (e.which) { 
 
     // user presses the "up arrow" key 
 
     case 38: 
 
     var focused = $(':focus'); 
 
     if (focused.hasClass('dropdown-toggle') || focused.is(':first-child')) { 
 
      $('.dropdown').find('.dropdown-item').first().focus(); 
 
     } else { 
 
      focused.prev().focus(); 
 
     } 
 
     break; 
 
     // user presses the "down arrow" key 
 
     case 40: 
 
     var focused = $(':focus'); 
 
     if (focused.hasClass('dropdown-toggle') || focused.is(':last-child')) { 
 
      $('.dropdown').find('.dropdown-item').first().focus(); 
 
     } else { 
 
      focused.next().focus(); 
 
     } 
 
     break; 
 
    } 
 
    }); 
 
});
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js"></script> 
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js"></script> 
 
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet" /> 
 
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js"></script> 
 

 

 

 
<div class="dropdown show"> 
 
    <a class="btn btn-secondary dropdown-toggle" href="https://example.com" id="dropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> 
 
    Dropdown link 
 
    </a> 
 

 
    <div class="dropdown-menu" role="menu" aria-labelledby="dropdownMenuLink"> 
 
    <a class="dropdown-item" href="#" tabindex="0">Action</a> 
 
    <a class="dropdown-item" href="#" tabindex="0">Another action</a> 
 
    <a class="dropdown-item" href="#" tabindex="0">Something else here</a> 
 
    </div> 
 

 
</div>

+0

謝謝。這是可能的箭頭鍵像bootstrap3? - http://getbootstrap.com/components/#dropdowns-example – user4812479812

+0

@ user4812479812確定我更新了我的代碼,您可以使用鍵盤上的向上箭頭/向下箭頭瀏覽列表項目。 –