如何通过键盘选择 bootstrap4 下拉菜单?

How to make bootstrap4 dropdown menu selectable by keyboard?

如何使 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>

使用 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>