如何编写jQuery手风琴脚本?实现问答区块交互需求
jQuery Accordion for Question Blocks
Got it, let's build a smooth, reusable accordion script tailored exactly to your HTML structure. I'll split this into CSS (for styling and transitions) and jQuery (for interactive logic) so it's easy to drop in and tweak.
Step 1: Add CSS for Initial State & Visual Feedback
First, we'll set up base styles to hide content by default, add a toggle icon, and create smooth animations:
/* Hide content container initially */ .question__wr { max-height: 0; overflow: hidden; transition: max-height 0.3s ease-out; /* Smooth expand/collapse */ margin-top: 10px; } /* Style the toggle icon (adjust to match your design) */ .question__icon { width: 18px; height: 18px; position: relative; cursor: pointer; transition: transform 0.3s ease; } /* Add a simple arrow using pseudo-elements (replace with your icon if needed) */ .question__icon::before { content: ''; position: absolute; top: 50%; left: 50%; width: 7px; height: 7px; border-right: 2px solid #555; border-bottom: 2px solid #555; transform: translate(-50%, -50%) rotate(45deg); } /* Active state: show content and rotate icon */ .question.active .question__wr { max-height: 400px; /* Adjust to fit your longest content block */ } .question.active .question__icon { transform: rotate(180deg); } /* Make title clickable and align with icon */ .question__title { cursor: pointer; display: flex; align-items: center; gap: 8px; /* Space between title text and icon */ margin: 0; }
Step 2: Write the jQuery Accordion Logic
This script handles the toggle behavior, ensures only one panel is open at a time (classic accordion style), and syncs the active state:
$(document).ready(function() { // Bind click event to both title and icon (since they're part of the question header) $('.question__title, .question__icon').on('click', function() { // Get the parent question block const $targetQuestion = $(this).closest('.question'); // Close all other open question blocks $('.question').not($targetQuestion).removeClass('active'); // Toggle the active state of the clicked question $targetQuestion.toggleClass('active'); }); });
How It Works
- Initial State: All
.question__wrcontainers are hidden withmax-height: 0to enable smooth transitions. - Click Trigger: Clicking either the title or icon triggers the toggle action.
- Single Open Panel: We first close all other open panels by removing the
activeclass, then toggle the class on the clicked panel. - Smooth Animation: The
max-heighttransition makes the expand/collapse feel natural instead of a sudden jump.
Quick Customization Tips
- If you want to allow multiple panels open at once, just remove the line
$('.question').not($targetQuestion).removeClass('active');. - Adjust the
max-heightvalue in.question.active .question__wrto fit your longest content block. - Modify the icon's color, size, or shape to match your site's design system.
内容的提问来源于stack exchange,提问作者paveell
相关产品推荐
相关产品推荐

