CSS关键帧动画仅在Hover时生效问题求助
Fix: Make Pulse Animation Run Only On Hover
Got it, let's sort this out! The problem with your current setup is that you’ve got the animation running nonstop by default, and only disabling it on hover. To flip this so the animation only plays when the user hovers, we just need to reverse the logic:
Step-by-Step Adjustments
- Remove the
animation: pulse 2s infinite;line from the base.pulse-animationclass (so elements don’t animate by default) - Add that exact animation rule to the
.pulse-animation:hoverselector instead (so animation triggers only on hover)
Updated Code
CSS
.pulse-animation { margin: 50px; display: block; width: 52px; height: 52px; border-radius: 50%; background: #ff8717; cursor: pointer; float: left; } .pulse-animation:hover { animation: pulse 2s infinite; } @keyframes pulse { 0% { -moz-box-shadow: 0 0 0 0 rgba(204, 169, 44, 0.4); box-shadow: 0 0 0 0 rgba(204, 169, 44, 0.4); } 70% { -moz-box-shadow: 0 0 0 30px rgba(204, 169, 44, 0); box-shadow: 0 0 0 30px rgba(204, 169, 44, 0); } 100% { -moz-box-shadow: 0 0 0 0 rgba(204, 169, 44, 0); box-shadow: 0 0 0 0 rgba(204, 169, 44, 0); } }
HTML
<span class="pulse-animation"></span> <img class="pulse-animation" src="https://randomuser.me/api/portraits/women/1.jpg" /> <img class="pulse-animation" src="https://randomuser.me/api/portraits/women/2.jpg" /> <img class="pulse-animation" src="https://randomuser.me/api/portraits/women/3.jpg" /> <img class="pulse-animation" src="https://randomuser.me/api/portraits/women/4.jpg" />
Why This Works
By moving the animation rule to the hover state, we tell the browser to only apply the pulse animation when the user’s cursor is over the element. The base class keeps all the core styling (size, border-radius, background, etc.) but no animation, so elements stay static until hovered.
内容的提问来源于stack exchange,提问作者Aly-Elgarhy
相关产品推荐
相关产品推荐

