带延迟的CSS动画问题:动画结束后需显示Div却仍隐藏的技术问询
Got it, let's figure out why your target div isn't showing up after the CSS animation ends. This is a common pitfall, but there are a few straightforward fixes depending on how you've set things up.
1. 别用display: none作为初始隐藏状态
If your target div starts with display: none, CSS animations won't work on it at all—this property yanks the element out of the document flow, so the animation engine can't interact with it.
Replace it with opacity: 0 or visibility: hidden to keep the element in the flow while hiding it initially. Here's a working example:
.target-div { opacity: 0; /* 初始隐藏 */ animation: fadeIn 1s 2s forwards; /* 2秒延迟,动画时长1秒,结束后保留最终状态 */ } @keyframes fadeIn { to { opacity: 1; /* 动画结束后变为可见 */ } }
The forwards value here is critical—it tells the browser to keep the element in the animation's final state instead of snapping back to the initial style.
2. Double-check animation-fill-mode
If you're already using opacity or visibility but still seeing the issue, you probably forgot to set animation-fill-mode: forwards. By default, animations revert to the element's original styles once they finish.
Fix it with this adjusted CSS:
.target-div { visibility: hidden; animation: showDiv 0.5s 3s forwards; } @keyframes showDiv { from { visibility: hidden; } to { visibility: visible; } }
3. Use JavaScript's animationend event (for flexible scenarios)
For more complex logic or if you need to work with display: none, listening for the animationend event in JS is a rock-solid approach. It avoids CSS limitations and lets you trigger extra actions if needed.
Example code:
<div class="animated-box">我是先执行动画的div</div> <div class="target-div" style="display: none;">我要在动画结束后显示</div> <script> const animatedEl = document.querySelector('.animated-box'); const targetEl = document.querySelector('.target-div'); animatedEl.addEventListener('animationend', () => { targetEl.style.display = 'block'; // 动画结束后切换显示状态 }); </script> <style> .animated-box { animation: slideAway 1s forwards; } @keyframes slideAway { from { transform: translateX(0); } to { transform: translateX(150px); } } </style>
Pro tip: If your element has multiple animations, use event.animationName to check which one finished, so you don't trigger the action accidentally.
4. Verify the animation is actually running
Sometimes the issue is simpler than you think—double-check these details:
- Did you accidentally set
animation-duration: 0s? - Is your CSS selector correctly targeting the element?
- Are other styles overriding your animation? (Use browser dev tools to inspect the element's computed styles.)
内容的提问来源于stack exchange,提问作者Rafael Don Escobar

