两种方式实现CSS动画

版权声明: https://blog.csdn.net/wlk2064819994/article/details/79955349

实现CSS动画有两种主要的方法:过渡动画(transition)和animation动画


第一种:过渡动画(transition)。

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>CSS动画之transition</title>
	<style>
		/*点击按钮执行动画*/
		.transi1{
			position: absolute;
			top: 260px;
			left:10px;
			width: 200px;
			height: 200px;
			background-color: red;
			transition: all 2s ease;
		}
		.transi2{
			background-color: blue;
			transform: rotate(45deg);
			left: 400px;
		}

		/*鼠标hover时的动画*/
		.hover{
			width: 200px;
			height: 200px;
			background-color: blue;
			transition: background-color 2s,width 2s;
		}
		.hover:hover{
			background-color: red;
			width: 300px;
		}

	</style>
</head>
<body>
 <div class="hover">第一个过渡动画</div>
 <hr>
 <button>执行动画</button>
 <div id="di1" class="transi1">第二个过渡动画</div>
 <script>
 	var btn  = document.getElementsByTagName("button")[0];
 	btn.addEventListener("click",function(){
 		var di = document.getElementById("di1");
 		di.setAttribute("class","transi1 transi2");
 	});
 </script>
</body>
</html>
 这个例子就比较直白地介绍了过渡(transition)形成的动画, 所谓过渡动画,也就是元素从一种样式逐渐改变为另一种样式的效果。
在第一个动画中就是hover前后两种样式。
在第二个动画中就是从样式"transi1"过渡到样式"transi1 transi2"。

要实现过渡动画有 两个必须点(和其他可选属性):
   1.指定要添加过渡效果的CSS属性(或者"all");

   2.指定过渡效果的持续时间。

注意:
1.transition属性写在过渡前后两个样式中的哪一个中无所谓。

2.在实现过渡动画时,很多初学者会把transition和transform搞混。要记住,transition才是实现过渡动画的关键,transform只是一个css转换属性(在本质上和其他css属性一样,可以当做transition-property的属性值)。



第二种:animation动画。

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>CSS动画之animation</title>
	<style>
		@keyframes wlk{
			100%{
				left: 300px;
				background-color: blue;
				transform: rotate(45deg);
			}
		}
		.transi1{
			position: absolute;
			top: 60px;
			left:10px;
			width: 200px;
			height: 200px;
			background-color: red;
		}
		.transi2{
			animation: wlk 2s;
			animation-fill-mode: forwards;
		}
	</style>
</head>
<body>
 <button>执行动画</button>
 <div id="di1" class="transi1">第二个过渡动画</div>

 <script>
 	var btn  = document.getElementsByTagName("button")[0];
 	btn.addEventListener("click",function(){
 		var di = document.getElementById("di1");
 		di.setAttribute("class","transi1 transi2");
 	});
 </script>
</body>
</html>
 这个例子介绍了animation形成的动画.
用animation动画的关键:
1.用@keyframes定义规则,并绑定到一个选择器上。
2.规定动画的名称(animation-name),规定动画的时长(animation-duration)。
也就是这个动画中的“animation: wlk 2s;”

注意:
1.@keyframes规则的写法。

2.animation和transition类似,是很多属性的简写形式,需要仔细掌握它们。



什么时候用transition过渡动画,什么时候用animation?

        其实如果掌握的熟练的话这两种动画是可以互相转换的。个人感觉在鼠标hover时的动画效果大多使用过渡动画,在需要鼠标触发时大多使用过渡动画;在网页加载后立即执行不需要手动触发时大多使用animation动画。


在上面的例子中我都用了JavaScript,其实在使用css动画时是可以不需要JavaScript的,这里为了效果才改成用按钮来触发动画。

猜你喜欢

转载自blog.csdn.net/wlk2064819994/article/details/79955349
今日推荐