CSS动画启动延迟问题:多背景图片切换动画修复咨询
修复CSS背景图片切换动画的初始延迟问题
问题根源
初始状态下所有图片都设置为opacity: 1,叠加显示;同时使用了alternate动画方向,导致第一次循环的时序逻辑和预期不符,前16秒无法触发正常的图片切换。
修复方案
- 设置初始可见状态:仅让第一张图片默认显示,其余图片初始隐藏
- 调整动画逻辑:移除
alternate方向,重新定义关键帧,让每张图在对应时间段完成「淡入-保持-淡出」的循环 - 对齐动画时序:保持原有的延迟时间,让每张图的显示周期衔接紧密
完整修复代码
CSS部分
* { margin: 0; padding: 0; box-sizing: border-box; } .container { height: 100vh; width: 100%; position: relative; } .overlay { background-color: rgba(0, 0, 0, 0.5); height: 100%; width: 100%; position: absolute; top: 0; left: 0; z-index: 10; } img { width: 100%; height: 100%; position: absolute; top: 0; left: 0; object-fit: cover; animation: fade 16s ease-in-out infinite; /* 移除alternate */ opacity: 0; /* 默认隐藏所有图片 */ } img:nth-of-type(1) { opacity: 1; /* 初始显示第一张图 */ animation-delay: 0s; } img:nth-of-type(2) { animation-delay: 4s; } img:nth-of-type(3) { animation-delay: 8s; } img:nth-of-type(4) { animation-delay: 12s; } @keyframes fade { 0% { opacity: 0; } 5% { opacity: 1; } /* 快速淡入 */ 20% { opacity: 1; } /* 稳定显示 */ 25% { opacity: 0; } /* 淡出 */ 100% { opacity: 0; } /* 剩余时间保持隐藏 */ }
HTML部分(无需修改)
<div class="container"> <div class="overlay"></div> <img alt="01" src="https://i.imgur.com/CzXTtJV.jpg"> <img alt="03" src="https://i.imgur.com/OB0y6MR.jpg"> <img alt="04" src="https://i.imgur.com/OnwEDW3.jpg"> <img alt="05" src="https://farm4.staticflickr.com/3075/3168662394_7d7103de7d_z_d.jpg"> </div>
效果说明
- 页面加载后立刻显示第一张图片
- 每4秒自动切换到下一张,切换过程包含平滑的淡入淡出效果
- 16秒后回到第一张图片,循环往复,无任何初始延迟
内容的提问来源于stack exchange,提问作者kerner1000
相关产品推荐
相关产品推荐

