当前位置:首页 > JavaScript

js 实现 dropdown

2026-01-31 23:32:18JavaScript

实现基础下拉菜单(Dropdown)

使用HTML、CSS和JavaScript创建一个简单的下拉菜单。以下是一个基础实现示例:

HTML结构

<div class="dropdown">
  <button class="dropdown-toggle">菜单</button>
  <ul class="dropdown-menu">
    <li><a href="#">选项1</a></li>
    <li><a href="#">选项2</a></li>
    <li><a href="#">选项3</a></li>
  </ul>
</div>

CSS样式

.dropdown {
  position: relative;
  display: inline-block;
}

.dropdown-menu {
  display: none;
  position: absolute;
  min-width: 160px;
  box-shadow: 0 8px 16px rgba(0,0,0,0.2);
  z-index: 1;
}

.dropdown-menu li {
  padding: 12px 16px;
  display: block;
}

.dropdown-menu li:hover {
  background-color: #f1f1f1
}

.show {
  display: block;
}

JavaScript逻辑

document.querySelector('.dropdown-toggle').addEventListener('click', function() {
  document.querySelector('.dropdown-menu').classList.toggle('show');
});

// 点击其他地方关闭菜单
window.addEventListener('click', function(event) {
  if (!event.target.matches('.dropdown-toggle')) {
    const dropdowns = document.querySelectorAll('.dropdown-menu');
    dropdowns.forEach(function(dropdown) {
      if (dropdown.classList.contains('show')) {
        dropdown.classList.remove('show');
      }
    });
  }
});

使用事件委托处理动态内容

对于动态生成的dropdown项目,使用事件委托更高效:

document.addEventListener('click', function(event) {
  // 切换菜单显示
  if (event.target.matches('.dropdown-toggle')) {
    event.target.nextElementSibling.classList.toggle('show');
  }

  // 点击菜单项
  if (event.target.matches('.dropdown-menu a')) {
    console.log('选择了:', event.target.textContent);
    event.target.closest('.dropdown-menu').classList.remove('show');
  }

  // 点击外部关闭
  if (!event.target.closest('.dropdown')) {
    document.querySelectorAll('.dropdown-menu').forEach(menu => {
      menu.classList.remove('show');
    });
  }
});

动画效果增强

为下拉菜单添加平滑的动画效果:

CSS添加过渡

.dropdown-menu {
  opacity: 0;
  transform: translateY(-10px);
  transition: opacity 0.3s, transform 0.3s;
  pointer-events: none;
}

.dropdown-menu.show {
  opacity: 1;
  transform: translateY(0);
  pointer-events: auto;
}

无障碍访问支持

确保下拉菜单对屏幕阅读器友好:

<div class="dropdown">
  <button 
    class="dropdown-toggle" 
    aria-expanded="false" 
    aria-haspopup="true"
    aria-controls="dropdown-menu"
  >
    菜单
  </button>
  <ul id="dropdown-menu" class="dropdown-menu" role="menu">
    <li role="none"><a href="#" role="menuitem">选项1</a></li>
    <li role="none"><a href="#" role="menuitem">选项2</a></li>
    <li role="none"><a href="#" role="menuitem">选项3</a></li>
  </ul>
</div>

更新JavaScript

document.querySelector('.dropdown-toggle').addEventListener('click', function() {
  const expanded = this.getAttribute('aria-expanded') === 'true';
  this.setAttribute('aria-expanded', !expanded);
  document.querySelector('.dropdown-menu').classList.toggle('show');
});

键盘导航支持

添加键盘交互支持:

js 实现 dropdown

document.querySelector('.dropdown-toggle').addEventListener('keydown', function(e) {
  const menu = this.nextElementSibling;

  if (e.key === 'Enter' || e.key === ' ') {
    e.preventDefault();
    const expanded = this.getAttribute('aria-expanded') === 'true';
    this.setAttribute('aria-expanded', !expanded);
    menu.classList.toggle('show');
  }

  if (e.key === 'ArrowDown' && menu.classList.contains('show')) {
    e.preventDefault();
    menu.querySelector('a').focus();
  }
});

document.querySelector('.dropdown-menu').addEventListener('keydown', function(e) {
  const items = this.querySelectorAll('a');
  const currentItem = document.activeElement;
  const currentIndex = Array.from(items).indexOf(currentItem);

  if (e.key === 'ArrowDown') {
    e.preventDefault();
    const nextIndex = (currentIndex + 1) % items.length;
    items[nextIndex].focus();
  }

  if (e.key === 'ArrowUp') {
    e.preventDefault();
    const prevIndex = (currentIndex - 1 + items.length) % items.length;
    items[prevIndex].focus();
  }

  if (e.key === 'Escape') {
    this.classList.remove('show');
    this.previousElementSibling.focus();
  }
});

这些实现方法涵盖了从基础功能到增强用户体验的多个方面,可以根据项目需求选择适合的方案或组合使用。

标签: jsdropdown
分享给朋友:

相关文章

js实现图片预览

js实现图片预览

使用FileReader API实现图片预览 通过FileReader对象读取用户选择的图片文件并显示预览: const input = document.getElementById('image…

js实现瀑布流

js实现瀑布流

实现瀑布流布局 瀑布流布局是一种常见的网页布局方式,常用于图片展示、商品列表等场景。以下是使用 JavaScript 实现瀑布流布局的几种方法。 纯 JavaScript 实现 通过计算元素的位置和…

js实现二叉树

js实现二叉树

二叉树的基本概念 二叉树是一种树形数据结构,每个节点最多有两个子节点,分别称为左子节点和右子节点。二叉树的常见操作包括插入、删除、遍历等。 二叉树的节点定义 在JavaScript中,二叉树的节点可…

js实现dh

js实现dh

JavaScript 实现 DH(Diffie-Hellman)密钥交换 Diffie-Hellman(DH)密钥交换是一种安全协议,允许双方在不安全的通信信道上建立一个共享密钥。以下是如何在 Jav…

js实现祖玛

js实现祖玛

实现祖玛游戏的核心思路 祖玛游戏的核心玩法是发射彩色珠子,形成三个或以上相同颜色的珠子即可消除。以下是使用JavaScript实现的基本框架。 游戏初始化 创建画布并初始化游戏状态: const…

js树实现

js树实现

树的基本概念 树是一种非线性的数据结构,由节点和边组成。每个节点包含一个值和指向子节点的引用。树的顶部节点称为根节点,没有子节点的节点称为叶节点。 树的实现方式 在JavaScript中,树可以通过…