在网页中实现动态加载条效果可以仅使用CSS完成,无需JavaScript。以下是几种常见的实现方法:
.loader {
width: 100%;
height: 4px;
background-color: #f3f3f3;
position: fixed;
top: 0;
left: 0;
z-index: 9999;
overflow: hidden;
}
.loader::before {
content: "";
display: block;
width: 30%;
height: 100%;
background-color: #3498db;
animation: loading 2s ease-in-out infinite;
}
@keyframes loading {
0% {
transform: translateX(-100%);
}
50% {
transform: translateX(300%);
}
100% {
transform: translateX(300%);
}
}
.loader {
width: 100%;
height: 4px;
position: fixed;
top: 0;
left: 0;
z-index: 9999;
background: linear-gradient(to right, #3498db, #3498db) no-repeat;
background-size: 0% 100%;
animation: loading 2s linear infinite;
}
@keyframes loading {
0% {
background-size: 0% 100%;
}
50% {
background-size: 100% 100%;
}
100% {
background-size: 0% 100%;
}
}
.loader {
width: 100%;
height: 4px;
position: fixed;
top: 0;
left: 0;
z-index: 9999;
background-color: #f3f3f3;
}
.loader::after {
content: "";
display: block;
width: 0%;
height: 100%;
background-color: #3498db;
animation: fullLoading 3s ease-out forwards;
}
@keyframes fullLoading {
0% {
width: 0%;
}
100% {
width: 100%;
}
}
将上述CSS代码添加到你的样式表中,然后在HTML中添加一个div元素:
<div class="loader"></div>
你可以通过修改以下属性来自定义加载条:
- 修改height
值调整加载条高度
- 修改background-color
或background
值改变颜色
- 调整animation
的持续时间(如2s
改为1s
)
- 使用animation-timing-function
改变动画速度曲线
position: fixed
)确保加载条始终可见以上方法都使用了纯CSS3动画特性,兼容现代浏览器。如需支持旧版浏览器,可能需要添加相应的浏览器前缀。