論CSS3 transform、translate、transition、animation
transform字義為“形變”,是指將某一元素進行2D/3D轉換,使其相應地旋轉、縮放、移動、傾斜。
常用方法有(詳見w3c Transform方法)
- scale(x,y) 2D縮放
- rotate(deg) 2D旋轉
- translate(x,y)也是其主要方法之一,是將元素相對位置進行位移。
*被 transform 的元素將預設擁有 “position: relative” 屬性。
transition義為“過渡”,是CSS3實現動畫的主要方法之一。
(從一種CSS樣式過渡變幻到另一種CSS樣式)
相應語法為:
transition: property duration timing-function delay;
- transition-property: 指定產生過度效果的CSS屬性
- transition-duration: 過渡時間。必需值。
- transition-timing-function: 速度曲線(如: linear 將產生勻速過渡效果)
- transition- delay: 延遲時間。可以為負,負值代表直接從效果(相應時間)中途開始。
*值得留意的是,在不指明 transition-property 的情況下,所有變化的CSS屬性都會觸發過渡效果。
出於CSS程式碼維護的角度考慮,使用 transition 時應指定 transition-property。
通常情況,我們可以將 transition 與 transform 聯合使用,以達到更好的效果:
為一個元素定義好 transition ,在合適的時機觸發 transform.
//滑鼠懸停時觸發元素360度旋轉
div {
width: 100px;
height: 100px;
transition: transform 1s ease, width 2s; //多個屬性可以用逗號隔開
}
div:hover {
transform: rotate(360deg);
width: 200px;
}
animation 顧名思義,它是CSS3的另一種動畫實現方式,且效果上更為靈活多變。
animation的動畫是由CSS3的 @key-frames 規則定義的:
@key-frames [animationName] {
from {
//css樣式
}
to {
//css樣式
}
}
from…to 亦可用百分比的形式進行多段劃分以精細效果。
然後,以
animation: [animationName] duration timing-function delay interation-count direction; 執行效果
- animation-name: 即@key-frames定義的[animationName],可任取;
- animation-duration: 執行一次動畫的時間;
- animation-timing-function: 時間曲線。同transition;
- animation-delay: 延遲時間。同transition;
- animation-interation-count: 播放次數。(如:infinite 即無限執行);
- animation-direction: 預設 normal。設定為 alternate 會反向執行。
* @key-frames 原則上是增添新屬性 或 覆蓋原有屬性。
1. 如在元素中原先設定了 transform 效果, @key-frames 中再次設定 transform 會覆蓋原定效果。
2. 在元素中設定如 top: 0 等效果,在 @key-frames 中新增如 bottom: 0 等效果, 可能無法得到預期的效果,因為top: 0 和 bottom: 0 會同時存在。
@key-frames move {
0% {
top: 0
}
100% {
bottom: 0 //可能會無效
}
div {
position: absolute;
top: 0;
animation: move 2s;
}
*文章為個人見解和實踐,錯誤之處歡迎指正。