本篇文章不一一列举CSS3动画的属性,若须要了解API,可前往 MDNcss
在开始栗子前,咱们先补补基础知识。前端
css3 动画分为如下两类:css3
animation: name duration timing-function delay iteration-count direction;web
ease 规定慢速开始,而后变快,而后慢速结束的过渡效果。bash
ease-in 规定以慢速开始的过渡效果。css3动画
ease-out 规定以慢速结束的过渡效果。dom
ease-in-out 规定以慢速开始和结束的过渡效果。ide
linear 动画从头至尾的速度是相同的。函数
cubic-bezier(n,n,n,n) 在cubic-bezier函数中本身的值,n取值为0~1学习
steps()
有些状况咱们须要确保动画结束后再进行另一些交互,可以使用该事件监听。
slide.addEventListener("webkitAnimationEnd", function() {
console.log('eeee') //动画结束再调用
});
复制代码
假如咱们须要实现一个这样简单的动画:
仔细观察上面的动画,咱们发现,它能够由如下3部分组成:
入场动画——从右往左移动
左右循环移动
逐帧动画
使用3个dom元素,最外层dom实现入场动画,第二层dom实现左右移动,第三层dom实现逐帧动画。
入场动画持续0.6s,只播放一次,左右移动以及逐帧动画持续2s,循环播放,代码以下:
.anima_entrance {
animation: anima_entrance .6s ease-in-out both;
}
.anima_move {
animation: anima_move 2s linear .6s infinite both;
}
.anima_sprite {
animation: anima_sprite 2s step-end .6s infinite both;
}
复制代码
使用下面这张雪碧图,经过改变background-position实现动画切换。
蹬蹬蹬,效果以下面所示,是否是很失望😞
缘由:因为animation默认以ease方式过渡,它会在每一个关键帧之间插入补间动画,因此动画效果是连贯性的。此时可使用steps()取消补间动画。
贴一个图:
接着,咱们将timing-function改为 step-end,效果以下:
animation: sprite 2s step-end .6s infinite both;
复制代码
出现想要的效果了哈~不错。
完整的css代码以下: (能够直接用下面的代码加上面的图片完成一个demo)
.anima_entrance {
position: absolute;
z-index: 3;
top: 5.1rem;
left: 4.05rem;
width: 12.9rem;
height: 19.1rem;
-webkit-animation: anima_entrance .6s ease-in-out both;
animation: anima_entrance .6s ease-in-out both;
}
.anima_move {
width: 218px;
height: 382px;
position: absolute;
z-index: 1;
top: 0;
left: 42px;
-webkit-animation: anima_move 2s linear .6s infinite both;
animation: anima_move 2s linear .6s infinite both;
}
.anima_sprite {
width: 218px;
height: 382px;
background: url(demo.png) no-repeat 0 0;
background-size: 25.8rem 19.1rem;
-webkit-animation: anima_sprite 2s step-end .6s infinite both;
animation: anima_sprite 2s step-end .6s infinite both;
}
@keyframes anima_entrance {
0% {
-webkit-transform: translate3d(18.75rem, 0, 0);
transform: translate3d(18.75rem, 0, 0);
}
100% {
-webkit-transform: translate3d(0, 0, 0);
transform: translate3d(0, 0, 0);
}
}
@keyframes anima_move {
0%, 16%, 42%, 74%, 100% {
-webkit-transform: translate3d(0, 0, 0);
transform: translate3d(0, 0, 0);
}
29% {
-webkit-transform: translate3d(-1rem, 0, 0);
transform: translate3d(-1rem, 0, 0);
}
87% {
-webkit-transform: translate3d(1rem, 0, 0);
transform: translate3d(1rem, 0, 0);
}
}
@keyframes anima_sprite {
0%, 16%, 42%, 58%, 74%, 100% {
background-position: -12.9rem 0;
}
8%, 50%, 66% {
background-position: 0 0;
}
}
复制代码
一个复杂的动画,经过梳理分层, 就能够简单的实现出来, 试着从新看看你的动画把~
欢迎关注「前端加加」, 按期分享优质文章
回复加群,邀你进技术群,长期技术交流学习