§ ITPOW >> 文档 >> CSS

CSS 3 动画问答-transition 与 animation 的区别

作者:vkvi 来源:ITPOW(原创) 日期:2021-8-23

有些效果上 transition 与 animation 确实都可以实现。

二者基本参数也差不多,但是 animation 多一个循环次数功能,还有可以自定义各个阶段(比如 0%、20%……)的过渡效果,还可设置轮流播放的方向,可以这样理解

  • transition 是两个样式之间的过渡效果。

  • animation 是一场“表演”。

还有一个就是触发条件,transition 必须要触发条件,才会动作,并不像 animation 直接写在那里都可以触发。

transition 触发条件一、伪类触发

<style type="text/css">
.c1 { width:50px; height:50px; background:red; transition:all 1s ease-out 0s; }
.c1:hover { width:100px; height:100px; background:green; }
</style>

<div class="c1"></div>

transition 触发条件二、JS 改变 class

<style type="text/css">
.c1 { width:50px; height:50px; background:red; }
.c2 { width:100px; height:100px; background:green; transition:all 1s ease-out 0s; }
</style>

<div class="c1"></div>

<script>
setTimeout(function () {
	document.querySelector(".c1").className = "c2";
}, 0);
</script>

注意,我们必须将 JS 代码放在 window.onload 或类似功能的代码中(比如上述是放在 setTimeout 中的。请参见:JavaScript 为什么 setTimeout 为 0,而不是直接调用?

也就是说要让页面加载完了,才去改变,才会有效。

transition 触发条件三、JS 改变属性值

<style type="text/css">
.c1 { width:50px; height:50px; background:red; transition:all 1s ease-out 0s; }
</style>

<div class="c1"></div>


<script>
setTimeout(function (){
	document.querySelector(".c1").style.height = "50px";
}, 2000); // 有效

window.onload = function () {
	document.querySelector(".c1").style.height = "100px";
}; // 有效
</script>

如上,先缓慢放大到 100px,再缩回 50px。

相关文章