实现点击Div栏展开隐藏内容时自动调整Div间距的功能
Expand/Collapse Div with Dynamic Spacing Adjustment
Got it, let's build this interactive expand/collapse feature that adjusts spacing automatically when content is shown or hidden. Here's a complete, clean implementation that fits your requirements:
HTML Structure
We'll create a container for all the toggle bars and their hidden content. Each toggle bar is paired with a hidden content div right after it:
<div class="container"> <div class="toggle-bar">Toggle Bar 1</div> <div class="hidden-content">Hidden content for bar 1 - this will slide in when you click the bar above</div> <div class="toggle-bar">Toggle Bar 2</div> <div class="hidden-content">Hidden content for bar 2 - blue background as you mentioned!</div> <div class="toggle-bar">Toggle Bar 3</div> <div class="hidden-content">Hidden content for bar 3 - feel free to customize styling</div> </div>
CSS Styling
We'll set up base styles, initial hidden state, and smooth transitions for a polished look. Notice we use max-height instead of display: none for smooth animation, and adjust margins dynamically:
.container { max-width: 800px; margin: 20px auto; } .toggle-bar { background: #f0f0f0; padding: 15px; margin: 10px 0; cursor: pointer; border-radius: 4px; transition: margin 0.3s ease; } .hidden-content { max-height: 0; overflow: hidden; background: #cce5ff; /* Blue background for hidden content */ padding: 0 15px; margin: 0 0 10px; border-radius: 0 0 4px 4px; transition: max-height 0.3s ease, padding 0.3s ease; } /* Active state: expand content and adjust spacing */ .toggle-bar.active + .hidden-content { max-height: 200px; /* Adjust based on your content size */ padding: 15px; } .toggle-bar.active { margin-bottom: 0; /* Remove bottom margin when content is expanded */ }
JavaScript Logic
We'll add click event listeners to each toggle bar to toggle the active state, which triggers our CSS transitions:
// Get all toggle bars const toggleBars = document.querySelectorAll('.toggle-bar'); toggleBars.forEach(bar => { bar.addEventListener('click', () => { // Close other open bars first (optional, remove if you want multiple open) toggleBars.forEach(otherBar => { if (otherBar !== bar) { otherBar.classList.remove('active'); } }); // Toggle current bar's active state bar.classList.toggle('active'); }); });
Key Notes
- Smooth Transitions: Using
max-heightandmargintransitions ensures the expand/collapse feels natural instead of abrupt. - Dynamic Spacing: When a bar is active, we remove its bottom margin so the hidden content sits flush against it, and the content's own margin maintains the spacing below.
- Optional Single Open: The code above closes other open bars when you click a new one. If you want multiple bars open at once, just remove the loop that removes the
activeclass from other bars. - Customization: Adjust colors, padding, max-height, and transition timings to match your design system.
内容的提问来源于stack exchange,提问作者Chris Nielsen
相关产品推荐
相关产品推荐

