transition 过渡
CSS3 新增了过渡属性,可以使用从一个状态变化到另一个状态时,变化更加的平滑;
CSS3 的过渡功能像是一种黄油,W3C 标准中是这样描述 transition 的:
- CSS3 的 transition 允许 CSS 的属性值在一定的时间区间内平滑的过渡;
- 这种效果可以在鼠标单击,获得焦点,对元素任何改变中触发,并平滑地以动画效果改变 CSS 的属性值;
transition 语法
语法:
transition: property duration timing-function delay
- 如果只提供一个参数,则为 transition-duration 的值定义;
- 如果只提供二个参数,则第一个为 transition-duration 的值定义,第二个为 transition-delay 的值定义
- 可以为同一元素的多个属性定义过渡效果,如果需要定义多个过渡属性且不想指定具体是哪些属性过渡,可以用 all 代替;
属性值
属性 描述 transition-property 1. 设置对象中的参与过渡的属性,默认值为:all 为所有可以进行过渡的 css 属性
2. 如果提供多个属性值,以逗号进行分隔transition-duration 1. 设置对象过渡的持续时间,默认值:0
2. 如果提供多个属性值,以逗号进行分隔transition-timing-function 1. 检索或设置对象中过渡的动画类型,默认值:ease;如果提供多个属性值,以逗号进行分隔
2. linear:线性过渡
3. ease:平滑过渡
4. ease-in:由慢到快
5. ease-out:由快到慢
6. ease-in-out:由慢到快再到慢
7. step-start:等同于steps(1, start)
8. step-end:等同于steps(1, end)
transition-delay 1. 设置对象延迟过渡的时间,默认值:0
2. 如果提供多个属性值,以逗号进行分隔需要特别说明的是,并不是所有的属性都可以进行过渡,只有属性是具有一个中点值的属性才能够进行过渡效果;因为这样才能通过不停的修改中间值从而实现过渡效果;例如 display: none | block 就没有中间值,所以无法应用过渡;具体支持过渡的属性可以参阅下表:
支持过渡的属性 background-color background-position border-bottom-color border-bottom-width border-left-color border-left-width border-right-color border-right-width border-spacing border-top-color border-top-width bottom clip color font-size font-weight height left letter-spacing line-height margin-bottom margin-left margin-right margin-top max-height max-width min-height min-width opacity outline-color outline-width padding-bottom padding-left padding-right padding-top right text-indent text-shadow vertical-align visibility width word-spacing z-index
多个元素过渡
-
如果要对多个 CSS3 属性应用过渡效果,直接用逗号分离开即可,这种主要是针对每个属性过渡的时间不同的情况下;
-
例如下面的例子:背景颜色过渡时间为 2s ,而宽度的过渡时间为 5s:
div { width: 100px; height: 100px; background-color: skyblue; transition: background-color 2s, height 5s; } div:hover{ height: 300px; background-color: pink; }
-
当然,如果每个属性的过渡时间都一样的话,那么直接使用 all 会更简洁一些;
hover 时过渡设置
-
可以在 hover 时对状态的变化设置一个过渡效果;
-
鼠标移开元素恢复时设置另一个过渡效果,例如:
div { width: 100px; height: 100px; background-color: skyblue; transition: all 5s /* 鼠标移走时的过渡 */ } div:hover{ height: 300px; background-color: pink; transition: all 2s; /* 鼠标 hover 时状态变化的过渡 */ }
过渡结束事件
-
有些时候,在 JS 中的某些操作需要过渡效果结束后再执行(如果过渡在完成前移除,过渡事件将不被触发);
-
事件类型提供了一个 transitionend 事件方便监听过渡效果是否结束,例如:
<style> div { width: 100px; height: 100px; background-color: skyblue; transition: all 3s } </style> <div id="oDiv"></div> <script> var div = document.getElementById("oDiv"); div.onclick = function(){ div.style.height = "400px"; } div.ontransitionend = function(){ console.log("过渡结束后触发"); } </script>
案例
-
示例代码
<style> .item1 { width : 200px; height : 100px; background-color: #333; /* transition-property: all; transition-duration: 1s; transition-timing-function: ease; transition-delay:.2s; */ /* 小技巧: 鼠标移入移出同时都有动画 transition 加在元素本身身上 */ transition: all 1s ease-in-out .2s; } .item1:hover { width : 400px; background-color: red; transform : translate(0, 20px); } </style> <!-- transform 位移 translate--> <div class="item1"></div>
-
效果展示
CSS 高级✍️ CSS3 的媒介 (media) 查询
上一篇