這篇博客意在用簡短的幾句話告訴你 CSS3特性 transition 的用法子漩。
transition 有4個性質(zhì):
名稱 | 描述 |
---|---|
transition-property | 要進(jìn)行改變的元素樣式 |
transition-duration | 完成transition的總時間 |
transition-timing-function | 變化的速度 |
transition-delay | 延遲多久觸發(fā)transition |
這4個性質(zhì)可以被分別設(shè)置最爬,也可以寫在一行當(dāng)中藻糖,看如下實(shí)例:
<button class="btn">TRANSITION</button>
.btn {
width: 400px;
height: 60px;
background-color: #3498db;
outline: none;
border: none;
color: #fff;
transition: background-color 1s ease .5s;
/* Separated usage of transition, which has the same effects of the one-line format.
transition-property: background-color;
transition-duration: 1s;
transition-timing-function: ease;
transition-delay: .5s;
*/
}
.btn:hover {
background-color: #e74c3c;
}
注釋里的4行和上面的一行實(shí)現(xiàn)的效果是一樣的
若想同時實(shí)現(xiàn)多個transition娶视,可以像下方一樣寫隘蝎,也可以用關(guān)鍵詞all购啄。
.btn {
width: 400px;
height: 60px;
background-color: #3498db;
outline: none;
border: none;
color: #fff;
transition: width 1s, background-color 1s ease .5s;
/* Separated usage of transition, which has the same effects of the one-line format.
transition-property: width, background-color;
transition-duration: 1s;
transition-timing-function: ease;
transition-delay: .5s;
*/
/* You can even change all declared css using "all"
transition: all 1s ease .5s;
*/
}
.btn:hover {
background-color: #e74c3c;
}
共有兩種常見的transition觸發(fā)方式:
- 在上方例子中,我使用了hover來觸發(fā)transition嘱么,這是最常見的使用方式之一狮含。
- 還有一種使用方式是,事先設(shè)置好transition曼振,通過javascript來監(jiān)聽DOM元素几迄,事件發(fā)生后通過js來改變設(shè)置了transition的元素的css。
- 這種方法更高級冰评,可實(shí)現(xiàn)的效果更多映胁。
除此之外,transition還可以與transform結(jié)合甲雅,來實(shí)現(xiàn)元素的移動解孙。
照舊坑填,附上我寫的一個demo,動手試一試更能明白用法 - CSS transition屬性嘗試 on JSfiddle