美文网首页
【融职培训】Web前端学习 第2章 网页重构14 css3动画效

【融职培训】Web前端学习 第2章 网页重构14 css3动画效

作者: lmonkey_01 | 来源:发表于2020-06-15 11:37 被阅读0次

    一、动画效果

    动画效果与过渡效果的区别在于,过渡效果一般用于用户与浏览器有交互的情况下,网页出现一些动态的变化。动画效果可以实现网页没有任何交互的情况下,自己就会展示动态效果。

    定义动画

    通过@keyframes可以定义动画效果,示例代码如下所示。

    1.box { 2    width: 200px; 3    height: 200px; 4    background-color: #00f; 5    animation: anim 5s linear 0.5s; 6} 7 8@keyframes anim{ 9    0%{10        transform: translate(0px,0px)11    }12    100%{13        transform: translate(900px,100px)14    }15}

    在上面的代码中,我们可以了解到css3动画的基本语法:

    首先,我们需要用@keyframes定义一个动画,在上面的代码中,我们定义的动画名字为anim。

    然后在花括号中定义动画的具体细节,0%位起始状态,100%为结束状态,我们也可以用其他的百分比定义动画在不同阶段的不同状态。

    最后,需要在元素选择器中调用这个动画,animation属性可以调用动画,第一个值是动画名称,后面的三个值分别是动画的时间,动画函数和延时时间,这个与我们之前学的过渡效果设置方法很类似。

    设置动画

    在上面的代码中,元素运行到100%的位置就会直接回到0%的位置,这样看起来效果很不平滑,为了让效果更连贯,我们可以让0%和100%的样式是相同的,代码如下所示。

    1.box { 2    width: 200px; 3    height: 200px; 4    background-color: #00f; 5    animation: anim 10s; 6} 7 8@keyframes anim { 9    0% {10        transform: translate(0px, 0px)11    }12    25%{13        transform: translate(500px, 0px)14    }15    50%{16        transform: translate(500px, 500px)17    }18    75%{19        transform: translate(0px, 500px)20    }21    100%{22        transform: translate(0px, 0px)23    }24}

    让动画更连贯

    在上面的代码中,元素经过了四次运动,最终回到了起始位置,我们还可以继续修改案例,让元素的动画效果更佳丰富。示例代码如下所示。

    1.box { 2    width: 200px; 3    height: 200px; 4    background-color: #00f; 5    animation: anim 10s linear; 6} 7 8@keyframes anim { 9    0% {10        transform: translate(0px, 0px) rotate(0);11    }12    25% {13        transform: translate(500px, 0px) rotate(360deg);14    }15    50% {16        transform: translate(500px, 500px) rotate(720deg);17    }18    75% {19        transform: translate(0px, 500px) rotate(1080deg);20    }21    100% {22        transform: translate(0px, 0px) rotate(1440deg);23    }24}

    循环动画

    我们还可以通过设置animation-iteration-count属性设置动画播放的次数,如果值为infinite,则动画不断地循环播放。示例代码如下所示。

    1.box {2    width: 200px;3    height: 200px;4    background-color: #00f;5    animation: anim 10s linear;6    animation-iteration-count:infinite;7}

    停止动画

    我们还可以通过设置animation-play-state属性让动画停止,代码如下所示

    1.box { 2    width: 200px; 3    height: 200px; 4    background-color: #00f; 5    animation: anim 10s linear; 6    animation-iteration-count: infinite; 7} 8.box:hover{ 9    animation-play-state: paused;10}

    这样当我们鼠标悬浮在元素之上的时候,动画就会停下来,当我们鼠标离开元素,动画又会开始运行。

    二、课后练习

    分阶段完成一个海盗船效果,具体阶段如下:

    完成波浪效果。

    完成船摆动的效果。

    添加鱼的效果。

    【融职教育】在工作中学习,在学习中工作

    相关文章

      网友评论

          本文标题:【融职培训】Web前端学习 第2章 网页重构14 css3动画效

          本文链接:https://www.haomeiwen.com/subject/wkycxktx.html