iT邦幫忙

2021 iThome 鐵人賽

DAY 11
0
Modern Web

CSS 讓你的網頁動起來系列 第 11

CSS微動畫 - Loading來了!轉啊轉啊~

Q: 從哪一種Loading開始呢?
A: 轉圈圈的Loading應該是基本?

之後將會進入一系列的Loading效果,本篇只會介紹一款,並對其做比較詳細的說明!直接開始囉~

<style>
  .container {
    position: relative;
    width: 55px;
    height: 60px;
    animation: round 1s linear infinite;
  }
  .dot {
    position: absolute;
    width: 15px;
    height: 15px;
    background-color: gray;
    border-radius: 50%;
  }
  .dot:nth-child(1) {
    top: 0;
    left: calc(50% - 7.5px);
  }
  .dot:nth-child(2) {
    top: calc(33.33% - 7.5px);
    left: calc(100% - 15px);
  }
  .dot:nth-child(3) {
    top: calc(66.67% - 5px);
    left: calc(100% - 15px);
  }
  .dot:nth-child(4) {
    top: calc(100% - 15px);
    left: calc(50% - 7.5px);
  }
  .dot:nth-child(5) {
    top: calc(66.67% - 5px);
    left: 0;
  }
  .dot:nth-child(6) {
    top: calc(33.33% - 7.5px);
    left: 0;
  }
</style>
<div class="container">
  <div class="dot"></div>
  <div class="dot"></div>
  <div class="dot"></div>
  <div class="dot"></div>
  <div class="dot"></div>
  <div class="dot"></div>
</div>

normal loading

Loading轉圈圈

第一款要利用animation實作loading轉圈圈,首先先將每個原點設定不同的透明度,再對外層的.container設定animation腳本,定義使用腳本名稱為loadingRotate

<style>
  .dot:nth-child(1) {
    opacity: .1667;
  }
  .dot:nth-child(2) {
    opacity: .3333;
  }
  .dot:nth-child(3) {
    opacity: .5;
  }
  .dot:nth-child(4) {
    opacity: .6667;
  }
  .dot:nth-child(5) {
    opacity: .8333;
  }
  .dot:nth-child(6) {
    opacity: 1;
  }
  .container {
    animation: loadingRotate 1s linear infinite;
  }
</style>

opacity loading

這時候因為還沒有定義@keyframes所以元素是不會動的,接著我們就要來寫這個動畫要怎麼演繹:在一開始的時候(0%)設定元素旋轉角度為0,當動畫演繹到最後的時候(100%)元素的旋轉角度設置為360deg,這樣每當元素執行一次動畫就會
由0deg演繹到360deg,腳本就完成了。

<style>
  @keyframes loadingRotate {
    0% {
      transform: rotate(0);
    }
    100% {
      transform: rotate(360deg);
    }
  }
</style>

rotate loading

animation參數回顧

每個動畫效果都是獨立且特別的,依照使用情境將動畫的屬性做修改。

.container {
  animation: loadingRotate 1s linear infinite;
}
  • loadingRotate
    這個值定義屬性animation-name,決定元素要演繹哪個腳本。

  • 1s
    這個值定義屬性animation-duration,元素演繹腳本的期間為一秒鐘,元素在一秒內會由0deg演繹到360deg,以達到Loading轉圈的效果。

  • linear
    這個值定義屬性animation-timing-function,預設值為ease會讓動畫演繹時由慢變快再變慢;由於希望Loading轉起來很順暢,則需要將值改為 linear讓動畫演繹時等速。

  • infinite
    這個值定義屬性animation-iteration-count,由於Loading轉圈效果是無限執行的,所以將預設的1改為infinite

(偷)(懶) 寫法

在腳本內有些過程是可以不寫的,不一定要寫滿0%到100%,如下面例子0%是可以被省略的,原因是元素預設transformrotate角度就是0,所以當動畫在演繹的時候,會從元素原本的狀態0deg演繹到360deg,效果是一樣的!

<style>
  @keyframes loadingRotate {
    100% {
      transform: rotate(360deg);
    }
  }
</style>

如果有寫錯的地方,歡迎點評! 會及時改進~
如果有更好的寫法,歡迎指教! 希望各位不吝賜教~
如果想看更多效果,歡迎敲碗! 提供示意圖小編寫寫看~
如果內容疑似侵權,拜託告知! 內容皆為小編理解後原創~
如果對你有點幫助,拿去用吧!


上一篇
CSS微動畫 - 了解Animation並做出更多效果吧!
下一篇
CSS微動畫 - Loading來了!七彩霓虹燈
系列文
CSS 讓你的網頁動起來30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言