网页需要加载大量数据或者网速较慢时,用户访问页面会出现较长的白屏时间,为了更好的显示效果,可以给网页增加进度条,实时显示加载进度。本文介绍几种常见的加载动画效果和实现方式
动态图片实现加载动画
定时器方式
设置一个定时器,在页面加载时显示动画,在规定时间后结束动画。缺点是每次加载都会执行定时器函数,可能在加载完成之前动画就结束了。
实现效果如下
UWeqeS.gif
css
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
.loading {
width: 100%;
height: 100%;
position: fixed;
top: 0;
left: 0;
background: #fff;
opacity: 1;
transition: 0.65s;
}
.loading .pic {
height: 64px;
width: 64px;
background: url("https://s1.ax1x.com/2020/07/19/UWE8xK.gif");
background-size: cover;
background-repeat: no-repeat;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
}
js
const loading = document.createElement("div");
loading.className = "loading";
loading.innerHTML = "
document.body.appendChild(loading);
setTimeout(() => {
loading.style.opacity = 0;
}, 3000);
通过加载状态事件制作进度条
document.onreadystatechange页面加载状态改变时触发
document.readyState返回当前文档状态(uninitialized 还未开始载入, loading 载入中,interactive 已加载,文档与用户可以交互,complete 载入完成)
实现效果
UWQPIS.gif
html
js
document.onreadystatechange = function () {
if (document.readyState === "complete") {
document.querySelector(".loading").style.opacity = "0";
}
};
css实现进度动画
实现效果
UWa3KU.gif
html
css
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
.loading {
width: 100%;
height: 100%;
position: fixed;
top: 0;
left: 0;
background: #fff;
opacity: 1;
transition: 0.65s;
display: flex;
align-items: center;
justify-content: center;
}
.loading div {
height: 50px;
width: 6px;
margin: 0 2px;
background: #0097e6;
border-radius: 3px;
/* x轴不动,变动y轴 */
transform: scaleY(0.4);
animation: load 1.2s infinite;
}
.loading div:nth-child(2) {
animation-delay: 0.1s;
}
.loading div:nth-child(3) {
animation-delay: 0.2s;
}
.loading div:nth-child(4) {
animation-delay: 0.3s;
}
@keyframes load {
0%,
40%,
100% {
transform: scaleY(0.4);
}
20% {
transform: scaleY(1);
}
}
js
document.onreadystatechange = function () {
if (document.readyState === "complete") {
document.querySelector(".loading").style.opacity = "0";
}
};
添加兼容性前缀