CSS进度条式Loading,加载到100%我们的距离就近了

3,372 阅读3分钟

「这是我参与11月更文挑战的第3天,活动详情查看:2021最后一次更文挑战

0.gif

进度条,大家应该都看到过,一个定宽的容器,里面按百分比展示进度,这就是进度条。

CSS + HTML可以很简单的实现进度条功能,下面我们看一个简单示例

示例一

<div class="progress" id="progress1"></div>

css

#progress1{
  position: relative;
  width: 200px;
  height: 20px;
  background: #dfdfdf;
}

#progress1:before{
  position: absolute;
  width: 20%;
  height: 100%;
  background: blueviolet;
  content: '20%';
  color: #fff;
  font-size: 12px;
  text-align: center;
}

20200106143058.png

这样,一个不太漂亮的进度条就出来了,是不是很简单了。

下面我来添加一个动画效果,让进度条动起来

@keyframes aw{
  from{
    width: 0
  }
  to{
    width: 100%
  }
}
#progress1:before{
  ...
  animation: aw 5s forwards;
}

1.gif

改变伪类:before的宽度,即可形成动画,同时让动画停留在最后一帧上面animation-fill-mode: forwards;(这里直接简写,到animation后)

示例二

<div class="progress" id="progress2">loading...</div>

css

#progress2{
  position: relative;
  width: 200px;
  height: 20px;
  background: #97ddff;
  margin-top: 20px;
}
#progress2:before{
  position: absolute;
  content: '';
  height: 2px;
  background: blueviolet;
  top: -2px;
  animation: aw 5s forwards;
  left: 0;
}
#progress2:after{
  position: absolute;
  content: '';
  height: 2px;
  background: blueviolet;
  bottom: -2px;
  animation: aw 5s forwards;
  left: 0;
}

2.gif

这个效果是不是很熟悉了,之前的 button :hover 事件里面有相同效果,还记得吗,变通一下就是一个进度条哦

示例三

<div class="progress" id="progress3"></div>

css

#progress3{
  position: relative;
  width: 100px;
  height: 100px;
  background: #97ddff;
  margin-top: 100px;
}
#progress3:before{
  position: absolute;
  content: '';
  height: 100%;
  background: blueviolet;
  animation: aw 5s forwards;
}
#progress3:after{
  position: absolute;
  content: '';
  height: 5px;
  width: 5px;
  transform: translate(-50%, -50%);
  border-radius: 100%;
  background: blueviolet;
  animation: surround 5s forwards;
}
@keyframes surround {
  0%{
    top: -10px;
    left: 10px;
  }
  25%{
    top: -10px;
    left: 110px;
  }
  50%{
    top: 110px;
    left: 110px;
  }
  75%{
    top: 110px;
    left: -10px;
  }
  100%{
    top: -10px;
    left: -10px;
  }
}

3.gif 这里2个动画,分别由:before宽度改变,和:after环绕运动形成的动画效果

环绕运动,计算好4个坐标点,平均分配时间。

同时,我们可以对:before动画进行优化,如果width是100%后,就又从100%到0。

4.gif

先让动画永久执行

/* 动画执行次数 */
animation-iteration-count: n|infinite;
@keyframes alrw{
  0%{
    width: 0;
    left: 0;
  }
  25%{
    width: 100%;
    left: 0;
  }
  50%{
    width: 100%;
  }
  51%{
    width: 0%;
    right: 0;
  }
  75%{
    right: 0;
    width: 100%;
  }
  100%{
    width: 100%;
  }
}

小结

本小结好像没有特别注意的知识点,但是还可以总结以下2点

1、CSS 伪类运用

2、animation 动画(仅执行一次:forwards,永久执行 infinite)

小伙伴们,有问题可以评论区留言哦,欢迎大家点评。需要源码的小伙伴可以购买,私信我哦。

谢谢大家一直以来的支持。