用纯JS实现动画效果代码量大,计算复杂.所以如今前端页面的动画效果通常都采用CSS来实现.css
CSS动画实现简单高效,可是在处理动画,控制动画过程上却缺乏一些有效手段.前端
例如咱们想在动画效果完成时调用回调函数来处理一些事务,会发现CSS并无提供直接的方法来让咱们使用.web
css动画效果有两种,即过渡和动画.函数
当元素从一种样式转变为另外一种样式,咱们为这种转变添加动画效果,这种效果就称做过渡.动画
CSS的过渡是经过 transtion 属性实现的.this
transtion属性必须包含如下两个值:spa
另外还有两个可选的属性值:code
下面是一个CSS过渡效果的例子:orm
div{ width: 100px; transition: width 2s; -webkit-transtion:width 2s; } div.hover{ width: 300px; }
当鼠标移动到此div上时,此div宽度会增长200px.blog
咱们为宽度添加上 2s 过渡效果.最后效果以下:
在实现比较复杂的动画时,单纯使用过渡已经没法达到目的,能够选择使用CSS的animation属性来定义动画效果.
要想使用animation属性,咱们必须先了解一下CSS3加入的@keyframes规则.
@keyframes规则用于建立动画,能够从动画运动状态的帧来定义动画.
以下即@kayframes定义动画的例子:
@keyframes show { from {color: red;} to {color: yellow;} } @-webkit-keyframes show /* Safari 与 Chrome */ { from {color: red;} to {color: yellow;} }
经过@keyframes咱们能够定义动画从开始到结束的样式变化 .
咱们也能够经过定义动画效果的百分比状态来定义动画样式,以下
@keyframes show { 0% {color: red;} 25% {color: yellow;} 50% {color: blue;} 100% {color: green;} } @-webkit-keyframes show /* Safari 与 Chrome */ { 0% {color: red;} 25% {color: yellow;} 50% {color: blue;} 100% {color: green;} }
在使用@keyframes定义了动画效果以后,咱们能够经过 animation 来将动画效果绑定到元素,以下:
div:hover{ animation:show 5s; }
具体效果以下:
动画文字
鼠标移动其上便可看到动画效果
以上就是CSS动画的简单介绍,另外CSS3还添加了transform属性,用于2D和3D转换,也被常常用来做为动画使用.
二.CSS动画的回调函数
像以上的CSS动画,若是想使用回调函数来控制动画完成后的事务处理,是比较麻烦的.
一.延时函数
不少人使用JS的延时函数 setTimtout() 来解决CSS动画的回调问题,相似以下的代码:
setTimtout(function(){ dosomething() //动画的回调函数 }, delaytime); //动画的持续时间
可是这种方法因为并非真正意义的回调,会形成如下几个问题:
所以,不建议使用延时函数做为动画的回调函数.
其实,JS提供了两个事件,能够完美的解决动画的回调函数问题,那就是 transtionend 和 animationend,当动画完成时,即会触发对应的事件.
咱们能够经过这两个事件轻松优雅的为动画添加回调函数.
具体用法以下:
transtionend
document.getElementById("myDIV").addEventListener("transitionend", myFunction); //myFunction即为动画回调函数
animationend
document.getElementById("myDIV").addEventListener("animationend", myFunction); //myFunction即为回调函数
咱们经过如下这个例子来体验这两个事件的具体使用:
<style> div#test { width:100px; height:100px; background:red; transition:width 2s; -webkit-transition:width 2s; /* Safari */ } div#test:hover { width:300px; } </style> </head> <body> <div id="test"> </div> <script> document.getElementById("test").addEventListener("transitionend", myFunction); function myFunction() { this.innerHTML = "回调函数触发div变为粉色"; this.style.backgroundColor = "pink"; } </script>
效果以下:
固然也可使用Jquery库的动画回调函数,很简单,代码相似以下,
$("#item").animate({height:"200px"}, function() { alert("hello"); });
以上就是关于CSS动画回调函数的一些知识,但愿对你有帮助.