JavaScript:Simon游戏多按钮代码近乎一致但运行结果差异显著
Hey there! Let's dig into why your red and yellow buttons aren't behaving like green and blue in your Simon game. Since two of the buttons work perfectly, the issue is almost certainly tied to a small inconsistency in how you've set up the problematic pair—let's break down the most likely culprits:
Double-check your element selectors in JavaScript
It's easy to mix up IDs or class names (they're case-sensitive!). Make sure you're targeting red and yellow correctly. Throw a quickconsole.logto confirm the elements are being found:const redBtn = document.getElementById('red-btn'); const yellowBtn = document.getElementById('yellow-btn'); console.log("Red button element:", redBtn); // Should not log null console.log("Yellow button element:", yellowBtn);Verify your CSS active/light-up styles
The "lighting up" effect relies on CSS transitions or state changes. Ensure red and yellow have the same.active(or equivalent) class styling as green and blue. Common misses include forgetting transitions, or having conflicting styles overriding the light-up state:/* Make sure this applies to ALL buttons */ .simon-btn.active { opacity: 0.6; box-shadow: 0 0 15px #fff; transition: all 0.3s ease-in-out; } /* Check for color-specific styles that might break things */ #red-btn.active { /* Should match the same transition/opacity rules as others */ background-color: #ff4444; }Inspect your sequence playback logic
When the game plays back the sequence, is it handling red and yellow exactly like green and blue? Look for typos in color names (e.g., "red" vs "Red") or missing cases in a switch statement:function playSequence(sequence) { sequence.forEach((color, index) => { setTimeout(() => { const btn = document.querySelector(`.simon-btn[data-color="${color}"]`); if (!btn) { console.error(`Button for color ${color} not found!`); return; } btn.classList.add('active'); setTimeout(() => btn.classList.remove('active'), 400); }, index * 700); }); }Test click event listeners
Confirm that red and yellow buttons are firing the correct input handler. Maybe you forgot to attach the listener, or there's a typo in the handler function call:redBtn.addEventListener('click', () => handlePlayerInput('red')); yellowBtn.addEventListener('click', () => handlePlayerInput('yellow')); // Double-check handlePlayerInput is processing red/yellow correctly function handlePlayerInput(color) { console.log("Player pressed:", color); // Should log "red" or "yellow" when clicked // Rest of your input logic... }
If you can share snippets of your HTML (for the button elements), the CSS for their states, and the relevant JavaScript sections (sequence playback/input handling), we can pinpoint the exact issue even faster!
内容的提问来源于stack exchange,提问作者JonesCode

