js 实现折叠
使用 CSS 和 JavaScript 实现折叠效果
通过切换 CSS 类或直接修改样式,可以实现元素的折叠与展开效果。以下是两种常见方法:
方法一:切换 CSS 类控制显示/隐藏
<style>
.content {
max-height: 0;
overflow: hidden;
transition: max-height 0.3s ease-out;
}
.content.expanded {
max-height: 500px; /* 调整为实际内容高度 */
}
</style>
<button onclick="toggleCollapse()">切换折叠</button>
<div id="collapseContent" class="content">
<!-- 折叠内容 -->
</div>
<script>
function toggleCollapse() {
const content = document.getElementById('collapseContent');
content.classList.toggle('expanded');
}
</script>
方法二:动态计算高度实现平滑动画
function toggleCollapse(elementId) {
const element = document.getElementById(elementId);
if (element.style.maxHeight) {
element.style.maxHeight = null;
} else {
element.style.maxHeight = element.scrollHeight + 'px';
}
}
使用 details/summary 原生 HTML 元素
HTML5 原生支持折叠效果,无需 JavaScript:
<details>
<summary>点击展开/折叠</summary>
<p>折叠内容区域</p>
</details>
第三方库实现方案
使用 jQuery 的 toggle/slide 方法:
$('#toggleButton').click(function() {
$('#content').slideToggle(300);
});
使用 Bootstrap 折叠组件:
<button class="btn btn-primary" data-toggle="collapse" data-target="#demo">
折叠按钮
</button>
<div id="demo" class="collapse">
折叠内容
</div>
动画优化技巧
使用 will-change 属性提升性能:
.collapsible {
will-change: height;
transition: height 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}
考虑添加 ARIA 属性增强可访问性:

<button aria-expanded="false" aria-controls="content">
切换内容
</button>
<div id="content" hidden>...</div>
以上方法可根据具体需求选择,原生 details/summary 最简单但定制性差,CSS/JavaScript 方案提供更多控制,第三方库则适合已有相关技术栈的项目。






