如何使用 HTML、CSS 和 JavaScript 构建手风琴菜单

2025-06-04

如何使用 HTML、CSS 和 JavaScript 构建手风琴菜单

HTML、CSS 和 JavaScript 可以帮助你创建时尚且动态的网页元素。手风琴菜单就是其中一种元素。

在本教程中,我们将构建一个简单的手风琴菜单。

ezgif.com-gif-maker.gif

什么是手风琴?

在 UI 设计中,手风琴折叠面板是一种垂直堆叠的信息列表。每个列表都有一个指向相应内容的标签标题。默认情况下,内容是隐藏的。点击特定标签可以展开其内容。

手风琴折叠面板的一个常见用途是保存常见问题列表。点击任何问题都会切换至相应的答案。

您可以从 Codepen 获取该项目的代码

如何使用 HTML、CSS 和 JS 构建手风琴

我们首先定义标记。如果您使用的是 VSCode 之类的 IDE,并且安装了 emmet,请创建一个新的 index.html 文件,然后键入!以下内容并按 Enter。这将为您的项目创建 HTML 样板代码。

或者,您可以将以下代码复制到您的index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <link rel="stylesheet" href="styles.css">
</head>
<body>

  <script src="app.js" type="text/javascript"></script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

文件夹结构很简单。我们将创建一个名为 accordion 的文件夹。在该文件夹中,我们将创建三个文件:index.html、styles.css 和 app.js。我们还将像上面一样,将所有文件链接到 HTML marjup 中。

手风琴的 HTML 标记

手风琴面板的 HTML 也将会相当简单。

<body>


  <div class="accordion-body">
  <div class="accordion">
    <h1>Frequently Asked Questions</h1>
    <hr>
    <div class="container">
      <div class="label">What is HTML</div>
      <div class="content">Hypertext Markup Language (HTML) is a computer language that makes up most web pages and online applications. A hypertext is a text that is used to reference other pieces of text, while a markup language is a series of markings that tells web servers the style and structure of a document. HTML is very simple to learn and use.</div>
    </div>
    <hr>
    <div class="container">
      <div class="label">What is CSS?</div>
      <div class="content">CSS stands for Cascading Style Sheets. It is the language for describing the presentation of Web pages, including colours, layout, and fonts, thus making our web pages presentable to the users. CSS is designed to make style sheets for the web. It is independent of HTML and can be used with any XML-based markup language. CSS is popularly called the design language of the web.
</div>
    </div>
    <hr>
    <div class="container">
      <div class="label">What is JavaScript?</div>
      <div class="content">JavaScript is a scripting or programming language that allows you to implement complex features on web pages — every time a web page does more than just sit there and display static information for you to look at — displaying timely content updates, interactive maps, animated 2D/3D graphics, scrolling video jukeboxes, etc. — you can bet that JavaScript is probably involved. It is the third of the web trio.</div>
    </div>
    <hr>
    <div class="container">
      <div class="label">What is React?</div>
      <div class="content">React is a JavaScript library created for building fast and interactive user interfaces for web and mobile applications. It is an open-source, component-based, front-end library responsible only for the application’s view layer. In Model View Controller (MVC) architecture, the view layer is responsible for how the app looks and feels. React was created by Jordan Walke, a software engineer at Facebook. </div>
    </div>
    <hr>
    <div class="container">
      <div class="label">What is PHP?</div>
      <div class="content">PHP is a server-side and general-purpose scripting language that is especially suited for web development. PHP originally stood for Personal Home Page. However, now, it stands for Hypertext Preprocessor. It’s a recursive acronym because the first word itself is also an acronym.</div>
    </div>
    <hr>
    <div class="container">
      <div class="label">What is Node JS?</div>
      <div class="content">Node.js is an open-source, cross-platform, back-end JavaScript runtime environment that runs on the V8 engine and executes JavaScript code outside a web browser. Node.js lets developers use JavaScript to write command line tools and for server-side scripting—running scripts server-side to produce dynamic web page content before the page is sent to the user's web browser. Consequently, Node.js represents a "JavaScript everywhere" paradigm</div>
    </div>
    <hr>
  </div>
  </div>

  <script src="index.js" type="text/javascript"></script>
</body>
Enter fullscreen mode Exit fullscreen mode

此时,我们的页面看起来一片空白。

htmlook.png

使用 CSS 为手风琴添加样式

当然,手风琴折叠面板必须看起来美观。是时候添加一些 CSS 了。

@import url('https://fonts.googleapis.com/css2?family=Rubik:wght@300&display=swap');

/* Sets the background color of the body to blue. Sets font to Rubik */

body {
  background-color: #0A2344;
  font-family: 'rubik', sans-serif;
}

/* Aligns the heading text to the center. */

h1 {
  text-align: center;
}

/* Sets the width for the accordion. Sets the margin to 90px on the top and bottom and auto to the left and right */

.accordion {
  width: 800px;
  margin: 90px auto;
  color: black;
  background-color: white;
  padding: 45px 45px;
}
Enter fullscreen mode Exit fullscreen mode

应用所有这些样式后,我们的手风琴面板将如下所示

withcss1.png

现在我们需要开始处理内部工作。首先,我们将每个容器(包含标签和内容)定位为相对。这意味着我们现在可以将其子项相对于父项进行定位。

.accordion .container {
  position: relative;
  margin: 10px 10px;
}

/* Position the labels relative to the .container. Add padding to the top and bottom and increase font size. Also make it's cursor a pointer */

.accordion .label {
  position: relative;
  padding: 10px 0;
  font-size: 30px;
  color: black;
  cursor: pointer;
}
Enter fullscreen mode Exit fullscreen mode

现在注意区别

withcss2.png

下一步是在每个列表的末尾添加一个小“+”号。我们将使用 ::before 选择器来实现这一点。::before 和 ::after 选择器用于将内容放置在指定元素之前或之后。

这里,我们在标签前插入“+”。不过,我们将使用偏移属性“top”和“right”将其放置在最右角。


/* Position the plus sign 5px from the right. Center it using the transform property. */\

.accordion .label::before {
  content: '+';
  color: black;
  position: absolute;
  top: 50%;
  right: -5px;
  font-size: 30px;
  transform: translateY(-50%);
}

/* Hide the content (height: 0), decrease font size, justify text and add transition */

.accordion .content {
  position: relative;
  background: white;
  height: 0;
  font-size: 20px;
  text-align: justify;
  width: 780px;
  overflow: hidden;
  transition: 0.5s;
}

/* Add a horizontal line between the contents */

.accordion hr {
  width: 100;
  margin-left: 0;
  border: 1px solid grey;
}
Enter fullscreen mode Exit fullscreen mode

现在我们的应用程序看起来比以前好多了

nowbig.png

引入 JavaScript

到目前为止,我们的手风琴面板基本是静态的。为了让它在点击时显示内容,我们需要引入一些 JavaScript。

导航到您的 app.js 文件并输入以下内容

const accordion = document.getElementsByClassName('container');

for (i=0; i<accordion.length; i++) {
  accordion[i].addEventListener('click', function () {
    this.classList.toggle('active')
  })
}
Enter fullscreen mode Exit fullscreen mode

该脚本将通过“容器”类名访问我们所有的列表。

然后我们循环遍历列表。对于每个容器,我们只需为其添加一个事件监听器。当它被点击时,我们希望切换该元素的 class 为“active”。

现在我们要测试一下这个效果。点击第一个带有标签的容器What is HTML,打开 DevTool(Windows 上的 Chrome 浏览器请按 F12 键),然后在元素选项卡中检查它。

你应该找到已注册的活动类

活动.png

再次单击该元素将从active中删除该类。

完成应用程序

还有最后一件事要做。我们需要在样式表中创建一个 active 类。我们将定义当 JavaScript 在容器上切换该类时,手风琴折叠面板的外观。


/* Unhides the content part when active. Sets the height */

.accordion .container.active .content {
  height: 150px;
}

/* Changes from plus sign to negative sign once active */

.accordion .container.active .label::before {
  content: '-';
  font-size: 30px;
}
Enter fullscreen mode Exit fullscreen mode

这就是我们的最终应用程序。

ezgif.com-gif-maker.gif

总结

感谢您的阅读。希望您能从本教程中学到一些有用的知识。

如果您对此类内容感兴趣,我每天都会在我的博客上发布此类内容。

祝您度过愉快的一周。

附言:如果你正在学习 JavaScript,我创建了一本电子书,其中讲解了 50 个 JavaScript 主题,并配有手绘数字笔记。点击此处查看。

文章来源:https://dev.to/ubahthebuilder/how-to-build-an-accordion-menu-using-html-css-and-javascript-3omb
PREV
Styled Components 101 💅 Lecture 1: Introduction + Setup in a React Environment ⚛️ What are Styled Components? 💅 Installation 🖥 Getting Styled Components ready to work with React ⚛️ Creating our first styled component 🐣 Styling our component through props 💁‍♂️ Styling our component conditionally 💁 Inheriting styles from another component 👨‍👧‍👦 Can I use CSS preprocessors like SASS or LESS to write my styles instead of plain CSS? So, that means I can also add a nested pseudo-element to my styled component, right? 🤔
NEXT
20 个 JavaScript 面试问题及答案