如何独立修改元素CSS类:实现盒子点击切换颜色功能
Hey there! Let's get those boxes switching colors independently—you don't need a parent-child relationship at all, so that's not the issue here. The problem is likely that your current code is targeting both boxes at once when you click, instead of only the one you're interacting with. Here's how to fix it:
What's Going Wrong?
If both boxes change color when you click either, you're probably selecting both elements in your click handler and modifying their styles together. We need to make sure each box only reacts to its own clicks and updates its own color.
Solution 1: Use CSS Classes & Per-Element Event Listeners
This approach keeps your styles clean and uses JavaScript to toggle classes on individual boxes.
First, update your HTML to give boxes a shared class (so we can select them all) and keep your base CSS:
<p class="color-box"></p> <p class="color-box"></p>
.color-box { height: 50px; width: 100px; background-color: #555; /* Original color */ margin: 10px; cursor: pointer; } /* Define your alternate color tones */ .color-box.tone-1 { background-color: #777; } .color-box.tone-2 { background-color: #333; }
Then add JavaScript to bind a click event to each box, only modifying the clicked element:
// Grab all the color boxes const boxes = document.querySelectorAll('.color-box'); // Loop through each box and attach a click handler boxes.forEach(box => { box.addEventListener('click', function() { // Cycle through the color states if (this.classList.contains('tone-1')) { this.classList.remove('tone-1'); this.classList.add('tone-2'); } else if (this.classList.contains('tone-2')) { this.classList.remove('tone-2'); } else { this.classList.add('tone-1'); } }); });
Solution 2: Track Color State Directly in JavaScript
If you prefer not to use classes, you can track the color state for each box individually and update the inline style:
const boxes = document.querySelectorAll('.color-box'); // Define your color sequence: original -> tone 1 -> tone 2 const colorSequence = ['#555', '#777', '#333']; boxes.forEach(box => { // Initialize state for this specific box (starts at original color) let currentColorIndex = 0; box.addEventListener('click', () => { // Cycle to the next color in the sequence currentColorIndex = (currentColorIndex + 1) % colorSequence.length; // Update ONLY this box's background color box.style.backgroundColor = colorSequence[currentColorIndex]; }); });
Key Takeaway
The critical part here is using this (or event.target) to refer only to the box that was clicked, instead of selecting both boxes every time. Each box gets its own event handler and state, so they'll never interfere with each other.
内容的提问来源于stack exchange,提问作者script_breaker

