做完简单的加载效果后, 相信大家也想接着做一些更为复杂的效果我也是这么想的很多网页的加载动画都是由很多帧组成的, 要做到这种效果也不难, 说到底就是看你拆分动画的思路下面讲一个简单的例子
从左到右循序渐进的加载效果
一个典型的动画加载效果就是, 从左到右循序渐进的圆点加载效果如下:
那么怎么来实现这种效果呢?
绘制 n 个圆点
我这里绘制了 6 个圆点, 相信画圆点应该难不倒各位
- // CSS
- border-radius: 50%;
- background-color: gray;
如何做圆点的动画效果
我这里采用的方案是背景色变化, 每个圆点的颜色按照顺序依次由灰色变为红色那么具体怎么做呢?
定义关键帧
这里先定义关键动画帧, 描述背景色的变化过程
- @keyframes highlightBack {
- 0% { background-color: gray; }
- 100% { background-color: red; }
- }
应用动画
使用 animation 属性来应用 highlightBack, 并给到 0.2s 的一个动画时间
- .loading-animate {
- animation: highlightBack 0.2s ease forwards;
- }
设计动画过渡效果
我需要圆点的颜色一个个变化, 那么执行动画的时间点就必须不一样因此我给了每一个圆点不一样的 animation-delay 值
- // 比如第二个圆点, 我给它的动画时延是 0.2s, 相当于第一个圆点的动画执行完了, 才执行第二个圆点的动画
- .loading-point:nth-child(2) {
- animation-delay: 0.2s;
- }
一轮动画结束后怎么重新开始
页面加载的时间或长或短, 不可能动画只执行一轮就结束了所以我们需要让一轮动画结束后, 接着开始第二轮的动画具体怎么做呢?
我们可以监听最后一个圆点的动画结束事件 animationend, 然后在回调函数中移除动画类, 经过短暂的延时后, 重新添加动画类即可做到
- // 关键代码
- document.getElementById('last').addEventListener('animationend', () = >{
- var points = document.getElementsByClassName('loading-point');
- for (var i = 0; i < points.length; i++) {
- points[i].classList.remove('loading-animate');
- }
- setTimeout(() = >{
- for (var i = 0; i < points.length; i++) {
- points[i].classList.add('loading-animate');
- }
- },
- 500);
- });
根据状态隐藏圆点
这个跟上文说的是一样的, 当 document.readyState 的值为 complete 时, 隐藏圆点点击参考上文到此就完成了整个效果, 点击查看效果页面
来源: https://www.2cto.com/kf/201803/727298.html