動畫循環

開放

8.1 animation-iteration-count屬性

CSS動畫可以創造出動態的視覺效果,讓使用者界面更好。現在我們來看兩個控制動畫循環的關鍵屬性:animation-iteration-countanimation-direction

animation-iteration-count屬性定義了動畫播放的次數。這個屬性可以控制動畫是否只播放一次、多次或無限次。

語法:

element {
  animation-iteration-count: number | infinite;
}

解釋:

  • number: 動畫播放的次數(例如,1, 2, 3, 等等)
  • infinite: 動畫會無限次播放

範例:

HTML
<div class="box"></div>
CSS
@keyframes bounce {
  0% {
    transform: translateY(0);
  }

  50% {
    transform: translateY(-30px);
  }

  100% {
    transform: translateY(0);
  }
}

.box {
  width: 100px;
  height: 100px;
  background-color: #3498db;
  animation-name: bounce;
  animation-duration: 2s;
  animation-iteration-count: infinite;
}

代碼解釋:

  • @keyframes bounce: 定義了將元素上下移動的動畫
  • animation-iteration-count: infinite: 設置動畫無限次播放

8.2 animation-direction屬性

animation-direction屬性定義了動畫的播放方向。它可以指定動畫是按順序、反向或交替方向播放。

語法:

element {
  animation-direction: normal | reverse | alternate | alternate-reverse;
}

解釋:

  • normal: 動畫按順序播放(預設值)
  • reverse: 動畫反方向播放
  • alternate: 動畫在順序和反方向之間交替播放
  • alternate-reverse: 動畫從反方向開始,然後在反方向和順序之間交替播放

範例

順序和反向播放:

HTML
<div class="box1"></div>
<div class="box2"></div>
CSS
@keyframes moveRight {
  from {
    transform: translateX(0);
  }

  to {
    transform: translateX(100px);
  }
}

.box1, .box2 {
  width: 100px;
  height: 100px;
  background-color: #2ecc71;
  animation-name: moveRight;
  animation-duration: 2s;
  animation-iteration-count: infinite;
}

.box1 {
  animation-direction: normal;
}

.box2 {
  animation-direction: reverse;
}

代碼解釋:

  • .box1: 動畫按順序播放
  • .box2: 動畫反方向播放

方向交替:

HTML
<div class="box1"></div>
<div class="box2"></div>
CSS
@keyframes moveRight {
  from {
    transform: translateX(0);
  }

  to {
    transform: translateX(100px);
  }
}

.box1, .box2 {
  width: 100px;
  height: 100px;
  background-color: #3498db;
  animation-name: moveRight;
  animation-duration: 2s;
  animation-iteration-count: infinite;
}

.box1 {
  animation-direction: alternate;
}

.box2 {
  animation-direction: alternate-reverse;
}

代碼解釋:

  • .box1: 動畫在順序和反方向之間交替播放
  • .box2: 動畫從反方向開始,然後在反方向和順序之間交替播放

8.3 使用兩個屬性的範例

搖擺元素

  • 這個例子展示了移動向右和向左搖擺的元素:
HTML
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>搖擺元素</title>
    <style>
      @keyframes swing {
        0% {
          transform: rotate(0deg);
        }

        50% {
          transform: rotate(10deg);
        }

        100% {
          transform: rotate(0deg);
        }
      }

      .box {
        width: 100px;
        height: 100px;
        background-color: #e74c3c;
        animation: swing 1s infinite alternate-reverse;
      }
    </style>
  </head>
  <body>
    <div class="box"></div>
  </body>
</html>

代碼解釋:

  • @keyframes swing: 定義了會旋轉元素的動畫
  • .box: 應用動畫 的元素,持續1秒,無限次播放並從反方向開始
1
任務
Frontend SELF TW,  等級 24課堂 2
上鎖
方向交替
方向交替
1
任務
Frontend SELF TW,  等級 24課堂 2
上鎖
完整結合
完整結合
留言
  • 受歡迎
你必須登入才能留言
此頁面尚無留言