transition 字面意思就是「轉變、過渡」。它讓屬性值的改變不再是瞬間跳變,而是在指定時間內平滑地補間,是製作網頁微互動最省力的方式。真正動手試過之後,才會發現很多網路上很紅的效果,其實一行 transition 就能搞定。
background 就只讓背景色參與動畫。ease(先快後慢)、linear(等速)、ease-in(先慢後快)、ease-out(先快後慢)、ease-in-out(慢快慢)。也可以全部寫在一起:transition: all 0.3s ease;,其中 all 代表所有屬性都參與,0.3 是 duration,ease 是曲線。
.imgts {
width: 175px;
height: 175px;
background-color: white;
border: 2px solid blue;
display: block;
margin: 50px auto 0;
padding: 5px;
transform: rotate(10deg);
transition: all 0.5s ease-in;
box-shadow: 2px 2px 4px #9932CC;
}
.imgts:hover {
transform: rotate(0deg) scale(1.05);
box-shadow: 15px 15px 21px blue;
}
.divimg1 {
width: 200px;
height: 40px;
background-color: pink;
transition-property: background-color;
transition-duration: 0.3s;
transition-timing-function: ease;
}
.divimg1:hover {
background-color: yellowgreen;
}
第一段讓圖片在滑鼠移入時從傾斜 10 度回正、放大 5%,同時陰影被拉長拉淡,視覺上就像圖片被拎起來靠近使用者;第二段則示範如何只針對背景色做過渡,其餘屬性維持瞬間切換。
把這幾個屬性記熟,頁面上大部分「跟手」的細節都可以自己寫出來,不必再依賴 JavaScript。