DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> CSS入門知識 >> CSS進階教程
CSS 實作:不靠圖片,純 CSS 做出一個 Loading 動畫
編輯:CSS進階教程     

以前要做載入動畫,動輒就是一個 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 即可。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved