WordPress响应式折叠面板适配:桌面展开移动端收起并隐藏图标
Hey there! Let's get your Collapsematic panels behaving correctly across devices and hide that loc image. Here's a step-by-step fix that combines CSS (for fast, flicker-free styling) and JavaScript (for dynamic window resize handling):
1. Set Default Panel States with CSS Media Queries
First, we'll use CSS to define the default display state based on screen size—this avoids any unwanted content flash before JS loads. Add this to your WordPress theme's Additional CSS (Appearance > Customize > Additional CSS):
/* Desktop/Tablet: Keep collapematic panels expanded by default */ @media (min-width: 769px) { .collapsematic_content { display: block !important; } } /* Mobile: Keep collapematic panels collapsed by default */ @media (max-width: 768px) { .collapsematic_content { display: none !important; } } /* Hide the image with ID "loc" everywhere */ #loc { display: none !important; }
The !important ensures our styles override Collapsematic's default inline styles. Adjust the 768px breakpoint if you need a different tablet/mobile threshold.
2. Add JavaScript for Dynamic Window Resize Handling
If someone resizes their browser window between device sizes, we need to update the panel states dynamically. Create a small JS snippet and add it to your site (you can use a plugin like "Code Snippets" or add it to your theme's footer.php before the closing </body> tag):
document.addEventListener('DOMContentLoaded', function() { // Function to update panel visibility based on screen size function updateCollapsematicPanels() { const panels = document.querySelectorAll('.collapsematic_content'); const isMobile = window.innerWidth <= 768; panels.forEach(panel => { panel.style.display = isMobile ? 'none' : 'block'; }); } // Run on initial load updateCollapsematicPanels(); // Run when window is resized window.addEventListener('resize', updateCollapsematicPanels); });
Why Your Previous JS Might Have Failed
- DOM Loading Order: If your JS ran before the Collapsematic panels were rendered, it couldn't find the elements. Wrapping it in
DOMContentLoadedfixes this. - Plugin Style Overrides: Collapsematic adds inline
displaystyles, so using!importantin CSS or directly settingpanel.style.displayin JS ensures our changes stick.
3. Verify Collapsematic Plugin Settings
Double-check your Collapsematic plugin settings to make sure you haven't set a global "default collapsed/expanded" option that might conflict. If the plugin has a setting for default state, set it to expanded (since our CSS will override it on mobile).
That's it! This setup will make your panels expand on desktop/tablet, collapse on mobile, and hide the loc image permanently.
内容的提问来源于stack exchange,提问作者brambil

