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

时间:2017-05-18 12:14:16

标签: javascript bootstrap-4 twitter-bootstrap-4

如何通过键盘选择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>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

使用tabindex="0",您现在可以使用键tab然后键space来打开下拉列表,并使用tab来浏览列表项。

此外,您的源参考的顺序不正确,请检查下面的代码

&#13;
&#13;
$(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;
    }
  });
});
&#13;
<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>
&#13;
&#13;
&#13;