在网页应用中,数据加载过程往往伴随着等待,使用CSS实现进度条动画是一种轻量且高效的方案。它不依赖脚本,就能给用户明确的反馈。下面我们通过一个完整示例来了解具体做法。

一、进度条的基本结构
进度条通常由外层容器和内层填充块组成。外层设定固定宽度与背景色,内层通过宽度变化表示加载百分比。
<div class="progress"> <div class="progress-bar"></div> </div>
二、使用CSS绘制静态样式
我们先写好容器与进度条的静态外观,再添加动画。注意使用 <div> 作为结构标签,在描述时已做转义。
.progress {
width: 300px;
height: 20px;
background-color: #eeeeee;
border-radius: 10px;
overflow: hidden;
}
.progress-bar {
width: 0;
height: 100%;
background-color: #4caf50;
}
三、通过关键帧实现动画
使用 @keyframes 定义从零到百分百的宽度变化,并绑定到进度条上,即可形成连续加载效果。
@keyframes loading {
from { width: 0; }
to { width: 100%; }
}
.progress-bar {
animation: loading 2s linear infinite;
}
四、控制加载状态与速度
如果需要模拟有限加载,可以去掉 infinite 并设置 animation-fill-mode: forwards 保留结束状态。
.progress-bar {
animation: loading 3s ease-out forwards;
}
常见参数说明
| 属性 | 作用 |
|---|---|
| duration | 动画持续时间 |
| timing-function | 速度曲线,如 linear、ease |
| iteration-count | 播放次数,infinite 为循环 |
五、完整示例代码
将结构与样式结合,就能得到一个简洁的CSS进度条动画。
<style>
.progress {
width: 300px;
height: 20px;
background-color: #eeeeee;
border-radius: 10px;
overflow: hidden;
}
.progress-bar {
width: 0;
height: 100%;
background-color: #4caf50;
animation: loading 2s linear infinite;
}
@keyframes loading {
from { width: 0; }
to { width: 100%; }
}
</style>
<div class="progress">
<div class="progress-bar"></div>
</div>
通过上述方式,你可以灵活地调整颜色、圆角与动画时长,让数据加载提示更贴合项目风格。