如何为记忆游戏中匹配的卡片应用非hover触发的缩放效果
Got it, let's get that scale effect working when your memory game cards match! The issue with the hover-only CSS is that it's tied to mouse interaction—we need to switch to dynamically applying the effect via JavaScript when your matching logic fires. Here's how to do it step by step:
1. Adjust Your CSS
First, modify your existing grow class to separate the transition from the transformation. We'll use a second class to trigger the scale when cards are a match:
/* Keep the transition on the base class so it applies to any state changes */ .grow { transition: all .2s ease-in-out; } /* This class will be added dynamically when cards match */ .grow.matched-scale { transform: scale(1.1); }
If you already have a class for styling matched cards (like one that turns them green), you can combine the scale into that class instead of making a new one—just add the transform property to your existing matched card styles.
2. Trigger the Effect in Your JavaScript
Next, find the part of your code where you check if two cards are a match. When that condition is true, add the matched-scale class to both matching card elements. Here's a simplified example:
// Assume this is your match-checking logic function checkMatch() { const card1 = /* Your first selected card element */; const card2 = /* Your second selected card element */; if (card1.dataset.cardValue === card2.dataset.cardValue) { // Cards match! Apply the green styling AND the scale effect card1.classList.add('matched', 'matched-scale'); card2.classList.add('matched', 'matched-scale'); // If your .matched class already handles the green color, just add .matched-scale } }
Make sure your card elements already have the grow class applied (either in your HTML or via JavaScript when initializing the game) so the transition works smoothly.
Why This Works
Instead of relying on the :hover pseudo-class (which only responds to mouse movement), we're using JavaScript to apply a class directly when the match condition is met. The transition property in grow ensures the scale change animates smoothly over 0.2 seconds, just like your original hover effect.
内容的提问来源于stack exchange,提问作者JoshTheGray

