jQuery与JavaScript手风琴方案对比(一存bug一正常)及技术疑问
Great question! Let's break down exactly why this snippet works smoothly even with double-clicks—no full source code needed to figure it out.
First, let's unpack what the code does step by step:
var panel = this.nextElementSibling;grabs the panel element right after the clicked accordion trigger (the element you tap/click to open/close the panel).- The core logic lives in the
if/elsecheck onpanel.style.maxHeight:- If
panel.style.maxHeighthas a value (meaning the panel is currently expanded), we set it tonullto collapse the panel. - If it's empty (the panel is collapsed, either initially or after being closed), we set it to
panel.scrollHeight + "px"to expand the panel to match its content's full height.
- If
Now, why does this prevent double-click misfires?
Double-clicks trigger two rapid click events in quick succession. Here's how the code handles that flow:
- Initial state: Panel is collapsed,
panel.style.maxHeightis empty. - First click (double-click's first half): The code sees
maxHeightis empty, so it expands the panel by settingmaxHeightto the content's scroll height. - Second click (double-click's second half): Immediately after, the code checks
maxHeightagain—now it has a value from the first click. So it collapses the panel by settingmaxHeightback tonull.
The end result? After a double-click, the panel lands right back where it started (collapsed), instead of getting stuck open or behaving erratically. Each click reacts to the current real state of the DOM (not an external variable or counter), so even rapid clicks just toggle the state back and forth, canceling each other out.
This approach is reliable because it ties the logic directly to the element's actual displayed state, avoiding sync issues that can come with tracking state in separate variables.
内容的提问来源于stack exchange,提问作者Lukas Naujokaitis

