Transition 属性(过渡动画)
Transition 属性是可以让元素从一个状态转换成另一个状态,这就是过渡。
一、前言
之前有段时间总是混淆 transition 和 transform 属性的用法,这里有个方法,可供参考。 先说 transform,trans在英语词根中表示变化、运动,而 form 在英语词根中本身就是形状、形式的意思,那就不难理解 transform 是让形状变化起来了,于是它就是形状变换。 至于 transition,去查一下它的英语解释就一目了然了。这里是必应词典的解释:
a process or period in which something undergoes a change and passes from one state, stage, form, or activity to another
简单点说,就是经历了从一个状态、阶段、形式转换到另一个状态的一个过程或者一段时间。那么这样一个**“需要时间来转换的过程”**,不就描述了“过渡”二字的含义吗?
二、庖丁解牛
语法: transiton: transiton-property transiton-duration transiton-timing-function transiton-delay;
2.1 transiton-property (特性)
transition-property:all | none | <property> [ ,<property> ]*
规定设置过渡效果的 CSS 属性的名称。
all 为默认值,表示所有可以呈现动效的属性都去产生过渡动画。
none 表示没有过渡动画。
下表是可以产生动效的一些CSS属性值:
CSS属性名称 | 类型 |
background-color | color |
background-image | only gradients |
background-position | percentage, length |
2.2 transiton-duration (延续时间)
transition-duration:<time> [ , <time> ]*
规定完成过渡动画的延续时长。(单位为:秒或者毫秒)可以作用于所有元素,包括 :before 和 :after 伪元素。
默认值为 0,表示不产生过渡动效,而是即刻完成动画。
2.3 transiton-timing-function (速率变化函数)
transition-timing-function:linear | ease | ease-in | ease-out | ease-in-out | cubic-bezier(<number>, <number>, <number>, <number>)[ ,linear | ease | ease-in | ease-out | ease-in-out | cubic-bezier(<number>, <number>, <number>, <number>) ]*
规定过渡效果的速度曲线,过渡属性将随着时间的变化来改变其速度。
- liner 匀速 cubic-bezier(0, 0, 1, 1)
- ease 平滑过渡 cubic-bezier(0.25, 0.1, 0.25, 1)
- ease-in 加速 cubic-bezier(0.42, 0, 1, 1)
- ease-out 减速 cubic-bezier(0, 0, 0.58, 1)
- ease-in-out 先加速后减速 cubic-bezier(0.42, 0, 0.58, 1)
- cubic-bezier(n, n, n, n) 自定义一个贝瑟尔曲线,取值范围 [0, 1]。贝瑟尔曲线是什么?
2.4 transiton-delay (延迟时间)
transition-delay:<time> [ , <time> ]*
规定过渡动画延迟发生的时间。(单位为:秒或者毫秒)可以作用于所有元素,包括 :before 和 :after 伪元素。
默认值为 0,表示过渡动效即刻执行,没有延迟。
三、小试牛刀
写了一个小 demo,感受一下过渡动画的魅力。
html代码:
<h1 style="text-align:center;">小试牛刀</h1> <div class="container"> <button class="btn">开始</button> <br> <br> <div class="box">过渡</div> </div>
css代码:
* { margin: 0; padding: 0; } .container { position: relative; left: 50%; top: 10px; transform: translate(-50%); width: 500px; height: 500px; border-radius: 20px; border: 3px solid salmon; overflow: hidden; } .box { margin-top: 30px; margin-left: 30px; width: 100px; height: 100px; border-radius: 20px; border: 2px solid gold; background: #abcdef; line-height: 100px; text-align: center; font-size: 20px; /* 下面设置3个过渡动画 通过点击事件触发*/ transition: transform 2s ease 0.5s, backgroundColor 2s linear, height 1.5s ease-in-out, width 1.5s ease-in-out; } .btn { position: absolute; left: 50%; transform: translate(-50%, 10px); border-radius: 10px; border: 0; outline: 0; padding: 10px; }
js代码:
var oBtn = document.getElementsByClassName('btn')[0]; var oBox = document.getElementsByClassName('box')[0]; oBtn.onclick = function() { oBox.style.transform = 'translate(220px,220px) rotate(720deg)' oBox.style.backgroundColor = 'pink'; oBox.style.width = '200px'; oBox.style.height = '150px'; }