以下示範如何只用 CSS 的 transition 與 transform,做出 hover 時旋轉、變色、變形的平滑過渡效果。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css" media="screen">
.ddf{
margin: 0 auto;
width: 150px;
height: 125px;
background: #92B901;
color: #ffffff;
font-weight: bold;
font: 12px '微軟雅黑', Verdana, Arial, Helvetica, sans-serif;
padding: 20px 10px 0px 10px;
-moz-transition-property: width, height, -o-transform, background, font-size, opacity;
-moz-transition-duration: 1s, 1s, 1s, 1s, 1s, 1s;
transition-property: width, height, transform, background, font-size, opacity;
transition-duration: 1s, 1s, 1s, 1s, 1s, 1s;
border-radius: 5px;
opacity: 0.4;
}
.ddf:hover{
-moz-transform: rotate(360deg);
transform: rotate(360deg);
opacity: 1;
background: #1ec7e6;
width: 90px;
height: 60px;
font-size: 16px;
}
</style>
</head>
<body>
<div class="ddf">轉著好玩</div>
</body>
</html>
transform: rotate(360deg)——旋轉,預設順時針,參數為度數。
transition-property——指定要過濾(做過渡)的屬性,例如 width, height, transform, background, font-size, opacity。不列出的屬性會直接跳變,沒有動畫。
transition-duration——依序對應上面每個屬性的過渡時間,順序必須一一對齊。
opacity——不透明度,從 0.0(完全透明)到 1.0(完全不透明)。範例中初始為 0.4,hover 後升為 1,做出「浮現」的視覺感。
範例中把六個屬性與六段時間分開列出,其實可以用一行 transition 簡寫,而且現代瀏覽器不需要加前綴:
.ddf {
width: 150px;
height: 125px;
background: #92B901;
color: #fff;
opacity: 0.4;
border-radius: 5px;
transition: all 1s ease;
}
.ddf:hover {
transform: rotate(360deg);
opacity: 1;
background: #1ec7e6;
width: 90px;
height: 60px;
font-size: 16px;
}
transition: all 1s ease 會讓所有變化的屬性共用同一組時間與緩動曲線,程式碼短很多。若只想針對特定屬性做動畫(效能考量),仍建議明確列出,例如 transition: transform 1s ease, background-color 1s ease;。
另外提醒:旋轉 360 度在視覺上等於回到原位,若想做出真正的「翻轉」,實務上會搭配 backface-visibility 與 rotateY 來製作 3D 卡片翻面效果。