css的动画—animation

86 阅读3分钟

css的简单动画可以通过transition来实现,但transition不是很灵活,稍微复杂一点的动画可以用animation来实现。

一、animation的属性:

animation-name:绑定到元素的动画名称

// html文件:
<div className="slideInUp"></div>

// scss文件
.slideInUp{
    animation-name: SlideInUp;
    animation-duration: 0.5s; // 完成动画需要时间必不可少
    animation-timing-function: linear;
}

@keyframes MaskSlideInUp {
    from {
        transform: translate3d(0, 100%, 0);
        visibility: visible;
    }
    to {
        transform: translate3d(0, 0, 0);
    }
}

animation-duration:动画完成的时间

动画若想成功播放,必须要定义animation-duration 属性,这个属性用来设置动画完成一个周期需要花费的时间,单位为s或者ms代码示例如上

animation-timing-function:动画的速度曲线

可以取下面的几个值,默认为ease

描述
linear动画从开始到结束的速度是相同的
ease默认值,动画以低速开始,然后加快,在结束前变慢
ease-in动画以低速开始
ease-out动画以低速结束
ease-in-out动画以低速开始,并以低速结束
cubic-bezier(x1, y1, x2, y2)使用 cubic-bezier() 函数来定义动画的播放速度,参数的取值范围为 0 到 1 之间的数值

cubic-bezier() 函数定义了一个贝塞尔曲线(Cubic Bezier),贝塞尔曲线由四个点(P0,P1,P2 和 P3)定义,P0(0,0)和P3(1,1)分别表示初始时间初始状态和最终时间最终状态,P1(x1, y1)和P2(x2, y2)动态取值,取值范围是0到1,最终的曲线就是动画的速度曲线。

animation-fill-mode:设置当动画不播放时(开始播放之前或播放结束之后)动画的状态(样式)

设置当动画不播放时(开始播放之前或播放结束之后)动画的状态(样式),属性可选值有:

描述
none默认值。动画在动画执行之前和之后不会应用任何样式到目标元素
forwards当动画播放完成后,保持动画最后一个关键帧中的样式
backwards在 animation-delay 所指定的时间段内,应用动画第一个关键帧中的样式
both同时遵循 forwards 和 backwards 的规则
inherit从父元素继承该属性
initial设置该属性为它的默认值

animation-delay:定义动画开始播放前的延迟时间,单位为秒或者毫秒

语法格式:

animation-delay: time;

其中参数 time 就是动画播放前的延迟时间,参数 time 既可以为正值也可以为负值。参数值为正时,表示延迟指定时间开始播放;参数为负时,表示跳过指定时间,并立即播放动画。

animation-iteration-count:定义动画播放的次数

属性如下:

描述
n使用具体数值定义动画播放的次数,默认值为 1
infinite表示动画无限次播放

animation-direction:设置是否轮流反向播放动画

属性如下:

描述
normal默认值,以正常的方式播放动画
reverse以相反的方向播放动画
alternate播放动画时,奇数次(1、3、5 等)正常播放,偶数次(2、4、6 等)反向播放
alternate-reverse播放动画时,奇数次(1、3、5 等)反向播放,偶数次(2、4、6 等)正常播放

注意:alternate和alternate-reverse在设置animation-iteration-count大于1时才生效

animation-play-state:设置动画是播放还是暂停

属性如下:

描述
paused暂停动画的播放
running正常播放动画

二、动画的事件

animationstart:定义动画开始事件

例:

const div1 = document.getElementById("myDIV");  
div1.addEventListener("animationstart", myStartFunction);

const myStartFunction = () => {
    this.style.backgroundColor = "pink";
}

animationstart:定义动画重复时事件

例:

const div1 = document.getElementById("myDIV");  
div1.addEventListener("animationiteration", myRepeatFunction);

const myRepeatFunction = () => {
    this.style.backgroundColor = "blue";
}

animationstart:定义动画结束后事件

例:

const div1 = document.getElementById("myDIV");  
div1.addEventListener("animationend", myEndFunction);

const myEndFunction = () => {
    this.style.backgroundColor = "grey";
}

最后分享一个好用的网站,animate.style/ 很多动效可以复用里面的代码,很强👍