
本文将指导你如何使用 jQuery 和 CSS 创建一个带有图片的动态手风琴菜单。我们将使用图片作为菜单标题,并在点击时展开/折叠相应的内容区域,实现一个美观且交互性强的导航组件。
手风琴菜单的 HTML 结构
首先,我们需要定义 HTML 结构。手风琴菜单由多个 accordion-section 组成,每个 section 包含一个标题 accordion-section-title 和一个内容区域 accordion-section-content。标题部分我们将使用图片作为链接内容。
@@##@@This is first accordion section
@@##@@this is second accordian section
立即学习“前端免费学习笔记(深入)”;
@@##@@this is third accordian section
每个 accordion-section-title 的 href 属性指向对应 accordion-section-content 的 id。
CSS 样式
接下来,我们添加 CSS 样式来控制手风琴菜单的布局和外观。
.accordion {
overflow: hidden;
border-radius: 4px;
background: transparent;
}
.accordion-section-title {
width: 100%;
padding: 15px;
}
.accordion-section-title {
width: 100%;
padding: 15px;
display: inline-block;
background: transparent;
border-bottom: 1px solid #1a1a1a;
font-size: 1.2em;
color: #fff;
transition: all linear 0.5s;
text-decoration: none;
}
.accordion-section-title.active {
background-color: #4c4c4c;
text-decoration: none;
}
.accordion-section-title:hover {
background-color: grey;
text-decoration: none;
}
.accordion-section:last-child .accordion-section-title {
border-bottom: none;
}
.accordion-section-content {
padding: 15px;
display: none;
color: white;
}
.accordion-section {
background-image: url('https://i.pinimg.com/originals/16/51/a7/1651a7e049cf443edc1cffe560600e0f.jpg');
}这里设置了基本样式,包括背景、边框、内边距、文字颜色等。.accordion-section-content 初始设置为 display: none;,使其默认隐藏。.active 类用于高亮当前展开的标题。
jQuery 交互
最后,我们使用 jQuery 来实现点击标题展开/折叠内容区域的交互效果。
$(document).ready(function() {
$('.accordion-section-title').click(function(e) {
var currentAttrvalue = $(this).attr('href');
if ($(e.target).is('.active')) {
$(this).removeClass('active');
$('.accordion-section-content:visible').slideUp(300);
} else {
$('.accordion-section-title').removeClass('active').filter(this).addClass('active');
$('.accordion-section-content').slideUp(300).filter(currentAttrvalue).slideDown(300);
}
e.preventDefault(); // 阻止默认链接行为
});
});这段代码首先监听 .accordion-section-title 的点击事件。当点击发生时,获取当前点击标题的 href 属性值,然后判断当前标题是否已经处于激活状态 (.active)。
- 如果已经激活,则移除 .active 类,并使用 slideUp() 方法隐藏当前可见的内容区域。
- 如果未激活,则移除所有标题的 .active 类,并将当前点击标题添加 .active 类。然后,使用 slideUp() 方法隐藏所有内容区域,并使用 slideDown() 方法显示与当前点击标题 href 属性值匹配的内容区域。
e.preventDefault() 阻止了链接的默认行为,防止页面跳转。
引入 jQuery 库:
确保在 HTML 文件中引入 jQuery 库。
总结与注意事项
通过以上步骤,我们就成功创建了一个带有图片的 CSS 手风琴菜单。
注意事项:
- 图片尺寸: 确保所有图片尺寸一致,以保证手风琴菜单的美观性。
- CSS 样式: 根据实际需求调整 CSS 样式,例如背景颜色、字体大小、边框样式等。
- jQuery 版本: 确保使用的 jQuery 版本与代码兼容。
- 动画效果: 可以根据需要调整 slideUp() 和 slideDown() 方法的动画时长。
- 无障碍性: 考虑为手风琴菜单添加 ARIA 属性,以提高其无障碍性。
这个教程提供了一个基本的手风琴菜单实现,你可以根据自己的需求进行定制和扩展。












