這兩個屬性都做「動畫」,寫法也有點像,所以很多人會混淆。但它們的設計目的其實完全不同:transition 是「狀態轉換之間的過渡」,animation 是「自主播放的關鍵frame動畫」。搞懂這條界線,選用就不會再猶豫。
transition 是四個子屬性的簡寫:
transition-property: all; /* 要過渡的屬性 */ transition-duration: 0s; /* 持續時間 */ transition-timing-function: ease; /* 速度曲線 */ transition-delay: 0s; /* 延遲播放 */
它的本質是「當元素的狀態改變時,幫中間的過程補上動畫」。而狀態的改變通常來自偽類別(如 :hover、:active、:target)或由 JavaScript 動態設定。IE10 以上支援。
基本寫法:
div {
transition: <property> <duration> <timing-function> <delay>;
}
如果需要在動畫結束後做事,可以監聽 transitionend:
el.addEventListener('transitionend', updateTransition, true);
// WebKit 系瀏覽器需加上前綴
el.addEventListener('webkitTransitionEnd', updateTransition, true);
實例一:滑過時字級放大
#fade {
transition-property: font-size;
transition-duration: 0.5s;
transition-delay: 0;
font-size: 14px;
}
#fade:hover {
font-size: 36px;
}
實例二:一次過渡多個屬性,各自的時間可以分開寫
#nudge {
transition-property: color, background-color, padding-left;
transition-duration: 500ms, 500ms, 500ms;
}
#nudge:hover {
background-color: #efefef;
color: #333;
padding-left: 50px;
}
實例三:用 :target 做純 CSS 手風琴。這裡刻意用高度過渡,並搭配 overflow: hidden:
.accordion a {
display: block;
padding: 5px 10px;
background-color: #ccc;
color: #000;
text-decoration: none;
}
.accordion a:hover { background-color: #999; }
#accordion div {
height: 0; /* 先收起來 */
overflow: hidden;
transition: height 600ms ease;
}
#accordion div:target {
height: 110px; /* 被點擊對應時展開 */
}
animation 是七個子屬性的簡寫:
animation-name: none; /* 對應 @keyframes 的名稱 */ animation-duration: 0s; animation-timing-function: ease; animation-delay: 0s; animation-iteration-count: 1; /* 播放次數,可設 infinite */ animation-direction: normal; /* normal / reverse / alternate */ animation-fill-mode: none;
寫法:
animation: animation-name duration timing-function delay iteration-count animation-direction animation-fill-mode;
其中 animation-direction 有三種行為值得記住:normal 每次都從頭開始、reverse 每次都從反方向開始、alternate 則是正反往返。實例如下,一個左右來回的「掃描光」:
<div class="view_port"> <div class="polling_message">Listener for dispatches</div> <div class="cylon_eye"></div> </div>
.view_port {
background-color: black;
height: 50px;
width: 100%;
overflow: hidden;
}
.cylon_eye {
color: white;
height: 100%;
width: 80%;
background-color: red;
background-image: linear-gradient(to right,
rgba(0, 0, 0, 0.9) 25%,
rgba(0, 0, 0, 0.1) 50%,
rgba(0, 0, 0, 0.9) 75%);
animation: move_eye 4s linear 0s infinite alternate;
}
@keyframes move_eye {
from { margin-left: -20%; }
to { margin-left: 100%; }
}
同一組 keyframes 需要支援多瀏覽器時,記得補上 @-webkit-keyframes、@-moz-keyframes、@-o-keyframes 等前綴版本。
判斷方式其實很簡單:
· 只是 A 狀態到 B 狀態的過渡(滑鼠移入、點擊切換、展開收合),用 transition。程式碼短、性能好,而且不需要定義 keyframes。
· 需要多段中間狀態、需要重複播放、需要不中斷地自動循環,用 animation。因為它有 iteration-count 與 direction,transition 完全做不到無限循環。
兩者也常常合作。例如上方 #bounce 的例子就是用 animation 做彈跳,而 #spin 則是用 transition 搭配 transform: rotate(36000deg) 做出長時間的旋轉——同一個畫面上,兩種機制各司其職,一點都不衝突。