如何基于页面类存在性控制元素显示隐藏(CSS场景)
Hey there, let's break down solutions for both of your requirements clearly:
two时,隐藏类one CSS alone can't detect if an element with a specific class exists anywhere on the page, so we'll need a bit of JavaScript here. Here's a straightforward implementation:
First, wait for the DOM to fully load, then check if any element with the .two class exists. If not, hide all elements with the .one class.
document.addEventListener('DOMContentLoaded', () => { // Check if there's any element with class "two" const hasTwoClass = document.querySelector('.two') !== null; const oneElements = document.querySelectorAll('.one'); if (!hasTwoClass) { // Hide all .one elements oneElements.forEach(element => { // Option 1: Directly set display to none element.style.display = 'none'; // Option 2: Add a pre-defined CSS hidden class (better for separation of concerns) // element.classList.add('hidden'); }); } });
If you go with Option 2, add this to your CSS:
.hidden { display: none !important; /* Optional: Use !important if other styles are overriding */ }
current-cat-parent类时显示hide-it内容 This can be done with pure CSS if you leverage either ancestor class targeting or the :has() selector, depending on your page structure:
Scenario 1:
current-cat-parentis on a top-level container (like<body>)
If thecurrent-cat-parentclass is added to the<body>tag (or a parent container that wraps the.hide-itelement), use this CSS:/* Default state: Hide .hide-it */ .hide-it { display: none; } /* When the top-level container has current-cat-parent, show .hide-it */ body.current-cat-parent .hide-it { display: block; /* Adjust to flex/grid/etc. based on your layout */ }Scenario 2:
current-cat-parentis an element anywhere on the page (not a direct ancestor)
For cases wherecurrent-cat-parentis in a separate section (like a header) and.hide-itis in the middle of the page, use the CSS:has()selector (supported in modern browsers):.hide-it { display: none; } /* If any element with current-cat-parent exists on the page, show .hide-it */ :has(.current-cat-parent) .hide-it { display: block; }Note: If you need to support older browsers that don't support
:has(), use a small JS snippet to add a class to the<body>whencurrent-cat-parentexists, then use the Scenario 1 CSS:document.addEventListener('DOMContentLoaded', () => { if (document.querySelector('.current-cat-parent')) { document.body.classList.add('has-current-cat-parent'); } });Update your CSS to:
.hide-it { display: none; } body.has-current-cat-parent .hide-it { display: block; }
内容的提问来源于stack exchange,提问作者mukesh

