You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用键盘上下箭头导航Dropdown下拉菜单

Solution: Add Arrow Key Navigation to Your Dropdown Menu

Got it! Let's enhance your dropdown with smooth arrow key navigation while keeping all your existing click and Tab-based functionality intact. Here's the modified code with clear explanations:

Modified HTML

We’ll add tabindex="0" to the dropdown links to explicitly mark them as focusable (anchor tags are usually focusable by default, but this makes behavior consistent across browsers):

<div class="dropdown">
  <button onclick="myFunction()" class="dropbtn">Dropdown</button>
  <div id="myDropdown" class="dropdown-content">
    <a href="#home" tabindex="0">Home</a>
    <a href="#about" tabindex="0">About</a>
    <a href="#contact" tabindex="0">Contact</a>
  </div>
</div>

Updated CSS

We’ll add a focus style so users can clearly see which dropdown item is currently selected via keyboard:

.dropbtn {
  background-color: #3498DB;
  color: white;
  padding: 16px;
  font-size: 16px;
  border: none;
  cursor: pointer;
}
.dropbtn:hover, .dropbtn:focus {
  background-color: #2980B9;
}
.dropdown {
  position: relative;
  display: inline-block;
}
.dropdown-content {
  display: none;
  position: absolute;
  background-color: #f1f1f1;
  min-width: 160px;
  overflow: auto;
  box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
  z-index: 1;
}
.dropdown-content a {
  color: black;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
}
.dropdown a:hover, .dropdown a:focus {
  background-color: #ddd;
}
.show {display: block;}

Enhanced JavaScript

We’ll add keyboard event listeners to handle arrow key navigation, Esc key to close the menu, and manage focus properly:

function myFunction() {
  const dropdown = document.getElementById("myDropdown");
  dropdown.classList.toggle("show");
  
  // Auto-focus the first item when the dropdown opens
  if (dropdown.classList.contains('show')) {
    dropdown.querySelectorAll('a')[0].focus();
  }
}

// Handle keyboard navigation for the dropdown
document.addEventListener('keydown', function(event) {
  const openDropdown = document.querySelector('.dropdown-content.show');
  if (!openDropdown) return; // Exit if no dropdown is open
  
  const links = openDropdown.querySelectorAll('a');
  const currentFocusedIndex = Array.from(links).findIndex(link => document.activeElement === link);

  switch(event.key) {
    case 'ArrowDown':
      event.preventDefault(); // Prevent page scrolling
      const nextIndex = (currentFocusedIndex + 1) % links.length; // Wrap to first if at last
      links[nextIndex].focus();
      break;
    case 'ArrowUp':
      event.preventDefault(); // Prevent page scrolling
      const prevIndex = currentFocusedIndex === 0 ? links.length - 1 : currentFocusedIndex - 1; // Wrap to last if at first
      links[prevIndex].focus();
      break;
    case 'Escape':
      // Close dropdown and return focus to the button
      openDropdown.classList.remove('show');
      document.querySelector('.dropbtn').focus();
      break;
  }
});

// Keep your original outside-click close functionality
window.onclick = function(event) {
  if (!event.target.matches('.dropbtn')) {
    var dropdowns = document.getElementsByClassName("dropdown-content");
    var i;
    for (i = 0; i < dropdowns.length; i++) {
      var openDropdown = dropdowns[i];
      if (openDropdown.classList.contains('show')) {
        openDropdown.classList.remove('show');
      }
    }
  }
}

Key Improvements:

  • Arrow Key Navigation: Press ↓ to move focus to the next dropdown item (wraps back to the first when at the end), and ↑ to move to the previous item (wraps to the last when at the start).
  • Esc Key Support: Press Esc to close the dropdown and shift focus back to the dropdown button.
  • Auto-Focus on Open: When you open the dropdown (via click or keyboard), the first item gets focus automatically for seamless keyboard flow.
  • Clear Focus Visuals: The updated CSS ensures focused dropdown items have a visible highlight, so users always know which item is selected.

内容的提问来源于stack exchange,提问作者Mihalma

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 08:37:30