以前要做載入動畫,動輒就是一個 GIF。純 CSS 的做法的好處很直接:沒有額外 HTTP 請求、可以無限縮放而不失真、顏色尺寸都能用變數調整。
整個動畫只有三個元素:一個外框圓環(bowl_ringG)、一個承接用的旋轉容器(ball_holderG)、以及一顆小白球(ballG)。讓容器以圓心為軸持續旋轉,白球自然就沿著圓周跑動。
#bowlG{
position:relative;
width:128px;
height:128px;
}
#bowl_ringG{
position:absolute;
width:128px;
height:128px;
border:11px solid #000000;
-moz-border-radius:128px;
-webkit-border-radius:128px;
border-radius:128px;
}
.ball_holderG{
position:absolute;
width:34px;
height:128px;
left:47px;
top:0px;
-webkit-animation-name:ball_moveG;
-webkit-animation-duration:2s;
-webkit-animation-iteration-count:infinite;
-webkit-animation-timing-function:linear;
-moz-animation-name:ball_moveG;
-moz-animation-duration:2s;
-moz-animation-iteration-count:infinite;
-moz-animation-timing-function:linear;
}
.ballG{
position:absolute;
left:0px;
top:-30px;
width:51px;
height:51px;
background:#FFFFFF;
-moz-border-radius:43px;
-webkit-border-radius:43px;
border-radius:43px;
}
接著定義各引擎的 keyframes,讓容器從 0 度轉到 360 度:
@-webkit-keyframes ball_moveG{
0%{ -webkit-transform: rotate(0deg) }
100%{ -webkit-transform: rotate(360deg) }
}
@-moz-keyframes ball_moveG{
0%{ -moz-transform: rotate(0deg) }
100%{ -moz-transform: rotate(360deg) }
}
結構如下:
<div id="bowlG">
<div id="bowl_ringG">
<div class="ball_holderG">
<div class="ballG"></div>
</div>
</div>
</div>
幾個實作細節值得注意:.ball_holderG 的 left: 47px 是為了讓旋轉軸落在圓環圓心;.ballG 的 top: -30px 讓球體中心貼齊圓環邊線;timing-function 選 linear 而非 ease,是因為載入動畫需要等速旋轉才不會看起來一顿一顿。範例為相容性保留了 -webkit-、-moz-、-o-、-ms- 前綴,現代瀏覽器只留 animation 與 @keyframes 即可。