Menu
CoddyTech

下拉菜单

本课属于 Coddy HTML 学习旅程的“JavaScript 实战”单元。第 15 课,共 27 课。

下拉菜单是一种用户界面组件,触发后会显示更多选项。它们常用于导航中,可以在不占用太多空间的情况下整理内容。

首先,我们来创建一个基本下拉菜单的 HTML 结构:

<div class="dropdown">
  <button class="dropdown-toggle">Menu</button>
  <div class="dropdown-menu">
    <a href="#">Option 1</a>
    <a href="#">Option 2</a>
    <a href="#">Option 3</a>
  </div>
</div>

现在,我们来添加 JavaScript 代码,以切换下拉菜单的显示状态:

// 获取下拉菜单的切换按钮
const dropdownToggle = document.querySelector('.dropdown-toggle');

// 获取下拉菜单
const dropdownMenu = document.querySelector('.dropdown-menu');

// 为切换按钮添加点击事件监听器
dropdownToggle.addEventListener('click', function() {
  // 切换下拉菜单上的 'show' 类
  dropdownMenu.classList.toggle('show');
});

最后,添加一些基础 CSS 来隐藏或显示下拉菜单:

.dropdown-menu {
  display: none;
}

.dropdown-menu.show {
  display: block;
}

点击“菜单”按钮时,下拉菜单会显示出来。再次点击它会隐藏菜单。

challenge icon

挑战

简单

创建一个下拉菜单,点击按钮时显示或隐藏。

步骤:

  1. 在 HTML 中:
    • 为按钮添加 onclick 属性,使其在点击时调用名为 toggleDropdown 的函数
  2. 在 JavaScript 中:
    • 创建一个名为 toggleDropdown 的函数
    • 在函数内,切换 ID 为 “myDropdown” 的元素上的 "show" 类

亲手试试

<!DOCTYPE html>
<html>
<head>
  <title>Save the Forests</title>
  <link rel="stylesheet" href="style.css">
</head>
<body>
  <header>
    <h1>Save the Forests</h1>
    <p>Even planting one or two trees makes a difference.</p>
  </header>

  <div class="dropdown">
    <button class="dropbtn">Learn More ▼</button>
    <div id="myDropdown" class="dropdown-content">
      <a href="#">Why forests matter</a>
      <a href="#">How to grow a tree</a>
      <a href="#">Community projects</a>
    </div>
  </div>

  <main>
    <section>
      <h2>Why Trees Are Important</h2>
      <p>
        Forests clean our air, give us oxygen, and are home to countless animals.  
        Each tree you plant helps fight climate change and supports life on Earth.
      </p>
    </section>
    <section>
      <h2> Start Small</h2>
      <p>
        Don’t wait for a big change. Start with just one or two trees in your yard or community.  
        Your small action inspires others!
      </p>
    </section>
  </main>

  <footer>
    <p> Together we can make the planet greener.</p>
  </footer>

  <script src="script.js"></script>
</body>
</html>
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

JavaScript 实战中的所有课

自己练习: Web 在线编辑器