如何使用div元素实现与SVG同款的骨架加载动画?
当然可以!用div结构实现同款加载动画完全没问题
你提到的那个SVG加载效果,本质就是底部对齐的不同高度柱状条+渐变扫过动画,用你给出的div结构(甚至可以补一个div来对应SVG里的5根柱子),结合CSS就能轻松实现,代码还比SVG更易读易维护。
下面是具体的实现代码:
HTML结构(补全为5根柱子,和SVG对应;如果要保留4根也可以调整高度)
<section class="bars"> <div></div> <div></div> <div></div> <div></div> <div></div> </section>
CSS样式(完整实现动画)
.bars { display: flex; gap: 10px; /* 对应SVG里柱子的间距,可按需调整 */ align-items: flex-end; /* 让柱子从底部对齐,还原SVG的布局 */ width: 200px; height: 200px; /* 和SVG的 viewBox高度一致 */ } .bars div { width: 25px; /* 对应SVG里的柱子宽度 */ background: linear-gradient(90deg, #f0f0f0 0%, #e0e0e0 50%, #f0f0f0 100%); background-size: 200% 100%; /* 让渐变宽度是柱子的2倍,方便动画移动 */ animation: sweep 2s linear infinite; } /* 给每个柱子设置对应SVG的高度 */ .bars div:nth-child(1) { height: 40px; } .bars div:nth-child(2) { height: 55px; } .bars div:nth-child(3) { height: 74px; } .bars div:nth-child(4) { height: 120px; } .bars div:nth-child(5) { height: 58px; } /* 渐变扫过的动画,和SVG里的animate逻辑一致 */ @keyframes sweep { 0% { background-position: -200% 0; } 100% { background-position: 100% 0; } }
关键细节说明
- 布局还原:用
align-items: flex-end让柱子从底部开始排列,完美匹配SVG里的rect元素位置逻辑 - 渐变动画:CSS线性渐变的颜色和位置完全对应SVG里的
<linearGradient>,background-size和@keyframes实现了和SVG中<animate>相同的扫过效果 - 高度匹配:每个柱子的高度直接对应SVG里rect的
height属性,保证视觉一致 - 可扩展性:如果要保留你原来的4根柱子,只需要调整
nth-child的高度值,或者删除第5个div即可
如果想要动画更有层次感,还可以给每个柱子加一点动画延迟,比如:
.bars div:nth-child(2) { animation-delay: 0.2s; } .bars div:nth-child(3) { animation-delay: 0.4s; } .bars div:nth-child(4) { animation-delay: 0.6s; } .bars div:nth-child(5) { animation-delay: 0.8s; }
这样柱子会依次动起来,视觉效果更活泼~
内容的提问来源于stack exchange,提问作者undefined
相关产品推荐
相关产品推荐

