WEB前端开发网页手风琴折叠效果代码
时间: 2024-02-26 07:57:50 浏览: 184
以下是一个简单的手风琴折叠效果的HTML、CSS和JavaScript代码示例:
HTML代码:
```
<div class="accordion">
<div class="accordion-item">
<div class="accordion-header">Section 1</div>
<div class="accordion-content">Content for section 1 goes here.</div>
</div>
<div class="accordion-item">
<div class="accordion-header">Section 2</div>
<div class="accordion-content">Content for section 2 goes here.</div>
</div>
<div class="accordion-item">
<div class="accordion-header">Section 3</div>
<div class="accordion-content">Content for section 3 goes here.</div>
</div>
</div>
```
CSS代码:
```
.accordion {
display: flex;
flex-direction: column;
}
.accordion-item {
border: 1px solid #ccc;
margin-bottom: 10px;
}
.accordion-header {
background-color: #eee;
padding: 10px;
cursor: pointer;
}
.accordion-header:hover {
background-color: #ddd;
}
.accordion-content {
padding: 10px;
display: none;
}
```
JavaScript代码:
```
const accordionHeaders = document.querySelectorAll('.accordion-header');
accordionHeaders.forEach(header => {
header.addEventListener('click', () => {
const accordionItem = header.parentElement;
const accordionContent = accordionItem.querySelector('.accordion-content');
accordionContent.classList.toggle('active');
if (accordionContent.classList.contains('active')) {
accordionContent.style.maxHeight = accordionContent.scrollHeight + 'px';
} else {
accordionContent.style.maxHeight = null;
}
});
});
```
这段代码使用了Flexbox布局和JavaScript事件监听器来实现手风琴折叠效果。当用户点击折叠标题时,对应的内容部分将展开或折叠。其中,CSS代码设置了默认的折叠样式,JavaScript代码则根据内容的高度来动态计算展开的高度。
阅读全文