思路
利用css动画和js定时器(setTimeout),实现简单的进度条。
优势
不使用 setInterval,减少js代码量,业务代码更加简洁。
示意图
上传中 | 上传成功 | 上传失败 |
---|---|---|
代码
html
<!-- img-wrap有两种状态:uploading(上传中)、uploadfailed(上传失败)-->
<div class='img-wrap uploading'>
<img src='' alt='' />
<div class='img-state'>
<!-- progress-bar 有三种状态:progress-bar-status0、progress-bar-status1、progress-bar-status2-->
<div class='progress-bar'>
<div class='progress-innerbar'>
</div>
</div>
</div>
</div>
scss
.img-wrap {
/*上传中、上传失败*/
&.uploading, &.uploadfailed {
/*黑色遮罩*/
&::before {
content: "";
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto;
background: rgba(0,0,0,0.3);
}
}
.img-state {
/*底部进度条*/
.progress-bar {
width: 8.8rem;
height: 0.4rem;
position: absolute;
left: 0;
right: 0;
bottom: 0.6rem;
margin: auto;
border-radius: 0.2rem;
background: rgba(255,255,255,0.72);
/*底部进度条(内部)*/
.progress-innerbar {
width: 0;
height: 0.4rem;
background: #FF5500;
border-radius: 0.2rem;
}
/*进度条初始状态*/
&.progress-bar-status0 {
.progress-innerbar {
width: 20%;
-webkit-transition: width .5s linear;
-moz-transition: width .5s linear;
-o-transition: width .5s linear;
transition: width .5s linear; /*动画时长500ms*/
}
}
/*上传失败,进度条60%*/
&.progress-bar-status1 {
.progress-innerbar {
width: 60%;
-webkit-transition: width .5s linear;
-moz-transition: width .5s linear;
-o-transition: width .5s linear;
transition: width .5s linear; /*动画时长500ms*/
}
}
/*上传成功,进度条100%*/
&.progress-bar-status2 {
.progress-innerbar {
width: 100%;
-webkit-transition: width .5s linear;
-moz-transition: width .5s linear;
-o-transition: width .5s linear;
transition: width .5s linear; /*动画时长500ms*/
}
}
}
}
/*上传失败*/
&.uploadfailed .img-state::after {
content: "上传失败";
position: absolute;
left: 0;
right: 0;
top: 50%;
margin: auto;
-webkit-transform: translateY(-50%);
transform: translateY(-50%);
display: block;
font-size: 1.1rem;
line-height: 2rem;
text-align: center;
color: #fff;
}
}
js
new Promise((resolve) => {
// 执行上传图片方法
uploadImage(base64) {
$('.progress-bar').addClass("progress-bar-status0"); // 开始上传,进度条状态变成status0
resolve()
}
}).then((result) => {
// 上传成功
if(result.rc == 1) {
// 上传成功,进度条状态变成status2
$('.progress-bar').removeClass("progress-bar-status0 progress-bar-status1").addClass("progress-bar-status2");
setTimeout(() => {
$('.img-wrap').removeClass("uploading uploadfailed");
$('.img-wrap').find('.img-state').remove();
}, 500) // 假延时500ms,因为css动画需要500ms
}
// 上传失败
else {
// 上传失败,进度条状态变成status1
$('.progress-bar').removeClass("progress-bar-status0 progress-bar-status2").addClass("progress-bar-status1");
setTimeout(() => {
$('.img-wrap').removeClass("uploading").addClass("uploadfailed");
}, 500) // 假延时500ms,因为css动画需要500ms
}
})