如何仅用CSS实现方块从左到右动画?解决速度过快问题
问题解决:方块动画移动速度过快的修复方案
问题根源
你遇到的部分方块移动过快问题,核心是动画时长的计算逻辑存在两个问题:
- Sass无参数的
random()返回0~1的小数,calc(random() * 50s)可能生成接近0的极短时长,加上$i(1~10)后,会出现1秒左右的动画时长,对应50vw的移动距离,速度自然过快。 calc(random() * 50s) + $i语法不规范,$i是纯数字,需要明确单位(秒)才能与时长值相加。
修正后的代码
以下是调整后的Sass代码,彻底解决速度过快问题,同时优化动画效果:
.slide-bl { padding: 0; margin: 0; width: 40px; height: 40px; background-color: rgba(255, 88, 0, .9); display: block; position: absolute; top: -40px; left: -40vw; z-index: 0; border-radius: 6px; } @for $i from 1 through 10 { .slide-bl:nth-child(#{$i}) { animation: slide-bl-#{$i} cubic-bezier(0.250, 0.460, 0.450, 0.940) infinite; // 固定时长范围:10~50秒,彻底避免极短时长 animation-duration: calc(random() * 40s + 10s); // 加大延迟范围,让方块出现时机更分散 animation-delay: calc(random() * -2s); left: calc(random() * 16vw + 20px); top: calc(random() * 50vh + 80px); width: random(15) + 40px; height: random(15) + 40px; } @keyframes slide-bl-#{$i} { 0% { opacity: 0; transform: translateX(0); } 50% { opacity: 1; } 100% { opacity: 0; transform: translateX(50vw); } } }
@for ($i = 0; $i < 10; $i++) <div class="slide-bl"></div> @endfor

关键修改说明
- 固定动画时长范围:
calc(random() * 40s + 10s)确保每个方块的动画时长在10~50秒之间,彻底杜绝极短时长导致的过快移动。 - 优化延迟范围:将
animation-delay调整为-2s,让方块的出现时机更分散,动画层次感更强。 - 移除冗余代码:删除了原代码中重复的
5s基础动画时长(后续被animation-duration覆盖,属于无效代码)。
进阶优化(可选)
如果想让动画更符合视觉逻辑(比如大方块移动更慢),可以根据方块尺寸动态调整时长:
// 示例:宽度越大,动画时长越长 animation-duration: calc((random() * 30s + 10s) + (#{random(15) + 40}px / 100 * 5s));
内容的提问来源于stack exchange,提问作者João Mello
相关产品推荐
相关产品推荐

