0

0

优化手风琴(Accordion)组件:实现单项展开功能

聖光之護

聖光之護

发布时间:2025-11-10 11:41:16

|

157人浏览过

|

来源于php中文网

原创

优化手风琴(Accordion)组件:实现单项展开功能

本教程旨在解决手风琴组件默认多项可同时展开的问题,通过引入事件委托机制,并优化javascript逻辑,确保在用户交互时,手风琴组件始终只保持一个面板处于展开状态。文章将详细阐述其实现原理、提供完整的htmlcssjavascript代码示例,并探讨相关最佳实践。

手风琴组件的单项展开需求

手风琴(Accordion)组件是网页中常见的一种UI模式,用于节省空间并组织内容。用户点击标题时,相关内容区域会展开或收起。然而,默认的实现方式通常允许用户同时展开多个手风琴面板,这在某些场景下可能导致界面混乱或信息过载。本教程将指导您如何修改现有的手风琴组件,使其每次只能展开一个面板,即当一个面板展开时,其他所有已展开的面板会自动收起。

核心概念:事件委托

在处理多个相似元素(如手风琴按钮)的事件时,为每个元素单独添加事件监听器可能会导致性能问题,尤其当元素数量较多或动态增减时。事件委托(Event Delegation)是一种更高效的模式,它利用事件冒泡机制,将事件监听器添加到它们的共同父元素上。当子元素上的事件被触发时,事件会冒泡到父元素,父元素上的监听器可以捕获这个事件,并通过 event.target 判断是哪个子元素触发了事件。

使用事件委托的优势:

  • 性能优化:只需要一个事件监听器,减少了内存占用。
  • 代码简洁:无需为每个元素编写重复的事件绑定代码。
  • 动态元素支持:对于通过JavaScript动态添加的元素,无需重新绑定事件。

实现单项展开逻辑

要实现手风琴的单项展开,核心逻辑在于:当用户点击一个手风琴按钮时,我们需要先将所有当前已展开的面板收起,然后再展开用户点击的那个面板。

具体步骤如下:

  1. 获取所有手风琴按钮:首先,我们需要获取页面上所有的手风琴按钮元素,以便在需要时遍历它们。
  2. 绑定事件监听器到父元素:将点击事件监听器绑定到所有手风琴按钮的共同父元素上(例如 main 元素)。
  3. 判断事件目标:在事件监听器内部,检查 event.target 是否是手风琴按钮。
  4. 关闭其他面板:如果 event.target 是手风琴按钮,则遍历所有手风琴按钮,对于那些不是当前点击按钮的,将其对应的内容面板收起,并移除其激活状态的CSS类。
  5. 切换当前面板:最后,切换当前点击按钮对应的内容面板的展开/收起状态,并切换其激活状态的CSS类。

代码实现

HTML 结构

手风琴的HTML结构通常包含一个按钮和一个内容区域,它们被包裹在一个父容器中。

多奥淘宝客程序API免费版 F8.0
多奥淘宝客程序API免费版 F8.0

多奥淘宝客程序免费版拥有淘宝客站点的基本功能,手动更新少,管理简单等优点,适合刚接触网站的淘客们,或者是兼职做淘客们。同样拥有VIP版的模板引擎技 术、强大的文件缓存机制,但没有VIP版的伪原创跟自定义URL等多项创新的搜索引擎优化技术,除此之外也是一款高效的API数据系统实现无人值守全自动 化运行的淘宝客网站程序。4月3日淘宝联盟重新开放淘宝API申请,新用户也可使用了

下载
General - AD rate $10 ~ 99% off
General Inbox
dd/mm/yyyy
These cookies allow us or our third party analytics providers to collect information and statistics on use of our services by you and other visitors. These information help us improve our services and products for the benefit of you and others. These cookies allow us or our third party analytics providers to collect information and statistics on use of our services by you and other visitors. These information help us improve our services and products for the benefit of you and others. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Qui sint, deserunt cumque nobis illo ut beatae impedit pariatur aliquid minus!
dd/mm/yyyy

CSS 样式

CSS样式负责手风琴的外观和展开/收起的动画效果。关键在于使用 max-height: 0 和 overflow: hidden 来隐藏内容,并通过 transition 属性实现平滑过渡。此外,为避免鼠标悬停时边框变化导致内容跳动,可以预先设置透明边框。

@import url('https://fonts.googleapis.com/css?family=Inter');
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

/* 滚动条样式 */
main div.accordion_container::-webkit-scrollbar,
main div.accordion_container .accordion_body .accordion_body_item .accordion_content .inner::-webkit-scrollbar {
  width: 4px;
}
main div.accordion_container::-webkit-scrollbar-track,
main div.accordion_container .accordion_body .accordion_body_item .accordion_content .inner::-webkit-scrollbar-track {
  background-color: #444444;
}
main div.accordion_container::-webkit-scrollbar-button:vertical:increment,
main div.accordion_container .accordion_body .accordion_body_item .accordion_content .inner::-webkit-scrollbar-button:vertical:increment {
  background-color: rgba(108, 92, 231, 0.65);
}
main div.accordion_container::-webkit-scrollbar-button:vertical:increment:hover,
main div.accordion_container .accordion_body .accordion_body_item .accordion_content .inner::-webkit-scrollbar-button:vertical:increment:hover {
  background-color: rgba(108, 92, 231, 1.00);
}
main div.accordion_container::-webkit-scrollbar-button:vertical:decrement,
main div.accordion_container .accordion_body .accordion_body_item .accordion_content .inner::-webkit-scrollbar-button:vertical:decrement {
  background-color: rgba(108, 92, 231, 0.65);
}
main div.accordion_container::-webkit-scrollbar-button:vertical:decrement:hover,
main div.accordion_container .accordion_body .accordion_body_item .accordion_content .inner::-webkit-scrollbar-button:vertical:decrement:hover {
  background-color: rgba(108, 92, 231, 1.00);
}
main div.accordion_container::-webkit-scrollbar-thumb,
main div.accordion_container .accordion_body .accordion_body_item .accordion_content .inner::-webkit-scrollbar-thumb {
  background-color: rgba(108, 92, 231, 0.65);
  border-radius: 10px;
}
main div.accordion_container .accordion_body .accordion_body_item .accordion_content .inner::-webkit-scrollbar-thumb:hover {
  background-color: rgba(108, 92, 231, 1.00);
}

/* 主容器样式 */
main {
  background-color: rgba(25, 25, 25, 0.8);
  display: grid;
  place-items: center;
  font-family: 'Inter';
  width: 100%;
  height: 100vh;
}

main div.accordion_container {
  background-color: #efefef;
  padding: 10px;
  width: 800px;
  overflow: auto;
  border-radius: 3px;
  position: relative;
}

main div.accordion_container #small {
  font-size: 12px;
  text-align: center;
}

main div.accordion_container #accordion_header {
  text-align: center;
  font-size: 18px;
  margin-top: 20px;
}

main div.accordion_container .accordion_body {
  padding: 20px 0 30px;
  overflow: auto;
}

main div.accordion_container .accordion_body .accordion_body_item:not(:last-child) {
  margin-bottom: 10px;
}

/* 手风琴按钮样式 */
main div.accordion_container .accordion_body .accordion_body_item .accordion_btn {
  width: 100%;
  background-color: gainsboro;
  /* 预设透明边框,防止hover时内容跳动 */
  border: none;
  border-left: 3px solid transparent;
  border-right: 3px solid transparent;

  outline: none;
  text-align: left;
  padding: 10px 20px;
  font-size: 16px;
  cursor: pointer;
  transition: background-color 300ms linear;
}

main div.accordion_container .accordion_body .accordion_body_item .accordion_btn:hover {
  background-color: silver;
  border-left-color: rgba(19, 2, 153, 1);
  color: rgba(19, 2, 153, 1);
  border-right-color: rgba(19, 2, 153, 1);
}

/* 箭头图标 */
main div.accordion_container .accordion_body .accordion_body_item .accordion_btn::before {
  content: '▼';
  float: right;
}

main div.accordion_container .accordion_body .accordion_body_item .accordion_btn.arrowClass::before {
  content: '▲';
}

/* 手风琴内容区域样式 */
main div.accordion_container .accordion_body .accordion_body_item .accordion_content {
  border-left: 3px solid #777;
  border-right: 3px solid #777;
  max-height: 0; /* 初始隐藏 */
  overflow: hidden;
  transition: max-height 450ms ease-in-out; /* 过渡动画 */
}

main div.accordion_container .accordion_body .accordion_body_item .accordion_content .inner {
  padding: 20px 15px;
  font-size: 14px;
  background-color: #777;
  color: #dfdfdf;
  height: 200px; /* 固定高度并允许滚动 */
  overflow: auto;
}

main div.accordion_container .accordion_body .accordion_body_item .accordion_content .inner .inner_datetime {
  text-align: right;
}

main div.accordion_container .accordion_body .accordion_body_item .accordion_content .inner .inner_body {
  margin-top: 20px;
  text-align: justify;
}

JavaScript 逻辑

以下是实现单项展开的关键JavaScript代码。它使用了事件委托,并在点击事件中遍历所有手风琴按钮,关闭非当前点击的面板。

// 获取所有手风琴按钮的集合
const accordions = document.querySelectorAll('.accordion_btn');

// 将事件监听器绑定到共同的父元素 `main`
document.querySelector('main').addEventListener('click', e => {
  // 检查点击事件的目标是否是手风琴按钮
  if (e.target.classList.contains('accordion_btn')) {
    // 遍历所有手风琴按钮,关闭非当前点击的面板
    accordions.forEach(button => {
      // 如果当前遍历的按钮不是被点击的按钮
      if (button !== e.target) {
        // 关闭其内容面板
        button.nextElementSibling.style.maxHeight = null;
        // 移除其激活状态的CSS类
        button.classList.remove('arrowClass');
      }
    });

    // 获取当前点击按钮旁边的内容面板
    let content = e.target.nextElementSibling;

    // 切换当前点击面板的展开/收起状态
    // 如果当前 max-height 等于 scrollHeight (已展开),则设为 null (收起)
    // 否则,设为 scrollHeight (展开)
    content.style.maxHeight = parseFloat(content.style.maxHeight) === parseFloat(content.scrollHeight) ? null : content.scrollHeight + "px";

    // 切换当前按钮的激活状态CSS类
    e.target.classList.toggle('arrowClass');
  }
});

代码解释:

  1. const accordions = document.querySelectorAll('.accordion_btn');:这行代码在脚本加载时一次性获取所有带有 accordion_btn 类的按钮元素,并存储在一个 NodeList 中。
  2. document.querySelector('main').addEventListener('click', ...):我们将点击事件监听器绑定到 main 元素上,这是所有手风琴按钮的共同祖先。
  3. if (e.target.classList.contains('accordion_btn')):在事件处理函数内部,我们首先检查实际触发点击事件的元素 (e.target) 是否包含 accordion_btn 类。这确保了只有点击手风琴按钮时才执行后续逻辑。
  4. accordions.forEach(button => { ... });:如果点击的是手风琴按钮,我们遍历之前获取到的所有手风琴按钮。
  5. if (button !== e.target):在这个循环中,我们判断当前遍历到的 button 是否就是用户点击的那个按钮。
  6. button.nextElementSibling.style.maxHeight = null;:如果 button 不是被点击的按钮,我们就将其紧邻的兄弟元素(即内容面板 accordion_content)的 maxHeight 设为 null,从而将其收起。
  7. button.classList.remove('arrowClass');:同时,移除这个非当前点击按钮的 arrowClass,使其箭头图标恢复到收起状态。
  8. let content = e.target.nextElementSibling;:在关闭所有其他面板后,获取当前被点击按钮的内容面板。
  9. content.style.maxHeight = parseFloat(content.style.maxHeight) === parseFloat(content.scrollHeight) ? null : content.scrollHeight + "px";:这行代码是切换当前面板的关键。它检查当前 maxHeight 是否已等于内容的实际滚动高度 (scrollHeight)。如果是,说明面板已经展开,我们将其设为 null 以收起;否则,将其设为 scrollHeight 以展开。parseFloat() 用于确保数值比较的准确性。
  10. e.target.classList.toggle('arrowClass');:最后,切换当前点击按钮的 arrowClass,更新其箭头图标。

注意事项与最佳实践

  • 初始状态:如果希望页面加载时所有手风琴都默认收起,请确保所有 .accordion_content 元素的 max-height 初始值为 0。
  • 动画平滑性:transition: max-height 450ms ease-in-out; 是实现平滑展开/收起动画的关键。调整 450ms 可以改变动画速度。
  • 性能考量:虽然事件委托减少了事件监听器的数量,但在每次点击时遍历所有手风琴按钮可能会在有大量手风琴时产生轻微的性能开销。对于大多数应用场景,这种开销是可接受的。
  • 可访问性(Accessibility):为了更好的用户体验和可访问性,建议为手风琴按钮添加适当的ARIA属性,例如 aria-expanded 和 aria-controls,并支持键盘导航。
    • aria-expanded="true/false" 指示面板是否展开。
    • aria-controls="id_of_content_panel" 将按钮与控制的内容面板关联起来。
  • CSS边框抖动:在CSS中为 .accordion_btn 预设 border-left: 3px solid transparent; 和 border-right: 3px solid transparent; 是一个很好的实践,可以避免在鼠标悬停时边框颜色变化导致元素宽度改变,从而引起布局抖动。

总结

通过采用事件委托模式并精心设计的JavaScript逻辑,我们成功地将手风琴组件从多项展开模式转换为单项展开模式。这种方法不仅提升了用户界面的整洁性,还优化了代码结构和性能。理解事件委托的原理及其在实际项目中的应用,对于前端开发者而言是一项宝贵的技能。结合清晰的HTML结构和响应式的CSS样式,您可以构建出功能强大且用户友好的手风琴组件。

相关专题

更多
js获取数组长度的方法
js获取数组长度的方法

在js中,可以利用array对象的length属性来获取数组长度,该属性可设置或返回数组中元素的数目,只需要使用“array.length”语句即可返回表示数组对象的元素个数的数值,也就是长度值。php中文网还提供JavaScript数组的相关下载、相关课程等内容,供大家免费下载使用。

541

2023.06.20

js刷新当前页面
js刷新当前页面

js刷新当前页面的方法:1、reload方法,该方法强迫浏览器刷新当前页面,语法为“location.reload([bForceGet]) ”;2、replace方法,该方法通过指定URL替换当前缓存在历史里(客户端)的项目,因此当使用replace方法之后,不能通过“前进”和“后退”来访问已经被替换的URL,语法为“location.replace(URL) ”。php中文网为大家带来了js刷新当前页面的相关知识、以及相关文章等内容

372

2023.07.04

js四舍五入
js四舍五入

js四舍五入的方法:1、tofixed方法,可把 Number 四舍五入为指定小数位数的数字;2、round() 方法,可把一个数字舍入为最接近的整数。php中文网为大家带来了js四舍五入的相关知识、以及相关文章等内容

727

2023.07.04

js删除节点的方法
js删除节点的方法

js删除节点的方法有:1、removeChild()方法,用于从父节点中移除指定的子节点,它需要两个参数,第一个参数是要删除的子节点,第二个参数是父节点;2、parentNode.removeChild()方法,可以直接通过父节点调用来删除子节点;3、remove()方法,可以直接删除节点,而无需指定父节点;4、innerHTML属性,用于删除节点的内容。

470

2023.09.01

JavaScript转义字符
JavaScript转义字符

JavaScript中的转义字符是反斜杠和引号,可以在字符串中表示特殊字符或改变字符的含义。本专题为大家提供转义字符相关的文章、下载、课程内容,供大家免费下载体验。

391

2023.09.04

js生成随机数的方法
js生成随机数的方法

js生成随机数的方法有:1、使用random函数生成0-1之间的随机数;2、使用random函数和特定范围来生成随机整数;3、使用random函数和round函数生成0-99之间的随机整数;4、使用random函数和其他函数生成更复杂的随机数;5、使用random函数和其他函数生成范围内的随机小数;6、使用random函数和其他函数生成范围内的随机整数或小数。

990

2023.09.04

如何启用JavaScript
如何启用JavaScript

JavaScript启用方法有内联脚本、内部脚本、外部脚本和异步加载。详细介绍:1、内联脚本是将JavaScript代码直接嵌入到HTML标签中;2、内部脚本是将JavaScript代码放置在HTML文件的`<script>`标签中;3、外部脚本是将JavaScript代码放置在一个独立的文件;4、外部脚本是将JavaScript代码放置在一个独立的文件。

653

2023.09.12

Js中Symbol类详解
Js中Symbol类详解

javascript中的Symbol数据类型是一种基本数据类型,用于表示独一无二的值。Symbol的特点:1、独一无二,每个Symbol值都是唯一的,不会与其他任何值相等;2、不可变性,Symbol值一旦创建,就不能修改或者重新赋值;3、隐藏性,Symbol值不会被隐式转换为其他类型;4、无法枚举,Symbol值作为对象的属性名时,默认是不可枚举的。

543

2023.09.20

php源码安装教程大全
php源码安装教程大全

本专题整合了php源码安装教程,阅读专题下面的文章了解更多详细内容。

7

2025.12.31

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
Sass 教程
Sass 教程

共14课时 | 0.7万人学习

Bootstrap 5教程
Bootstrap 5教程

共46课时 | 2.7万人学习

CSS教程
CSS教程

共754课时 | 17.2万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号