使用css animation 制作loading动画

53 阅读1分钟

效果

动画.gif

方法

  1. 使用Animation添加from 到 to 的动画
  2. 给每个子元素添加延迟

animation的使用

animation: 规则名 持续时间 重复次数 时间函数 动画方向 延迟时间

  • name: 哪一种规则 @keyframs xx,xx就是规则名
  • duration: 持续时间
  • timing-function:贝塞尔曲线,规定动画是从快到慢,还是匀速的,ease-in-out:平滑开始,平滑结束
  • delay: 延迟时间
  • interration-count: 重复次数 infinite是无限重复
  • direction: alternate 交替动画,从from-to 再to-from

总结

  • 动画主要改变了dot的缩放,无限播放,交替方向
  • dot都应用了相同的动画,只不过每个动画的延迟时间是不同的

代码

<!DOCTYPE html>
<html lang="en">

<head>
	<meta charset="UTF-8" />
	<meta http-equiv="X-UA-Compatible" content="IE=edge" />
	<meta name="viewport" content="width=device-width, initial-scale=1.0" />
	<title>loading</title>
	<style>
		.loading {
			text-align: center;
			margin-top: 100px;
		}

		.dot {
			display: inline-block;
			width: 8px;
			height: 20px;
			background: lightgreen;
		}
	</style>
	<!-- 下面为动画的实现 -->
	<style>
		.dot {
			border-radius: 5px;
			animation: loading 0.4s infinite alternate;
		}

		@keyframes loading {
			from {
				transform: scaleY(1);
				background-color: rgb(187, 255, 192);
			}
			to {
				transform: scaleY(1.5);
			}
		}

		.dot:nth-child(2) {
			animation-delay: 0.2s;
		}

		.dot:nth-child(3) {
			animation-delay: 0.4s;
		}

		.dot:nth-child(4) {
			animation-delay: 0.6s;
		}

		.dot:nth-child(5) {
			animation-delay: 0.8s;
		}
	</style>
</head>

<body>
	<div class="loading">
		<div class="dot dot1"></div>
		<div class="dot dot2"></div>
		<div class="dot dot3"></div>
		<div class="dot dot4"></div>
		<div class="dot dot5"></div>
	</div>
</body>

</html>