7.1 Animate.css

官網

官網:https://animate.style/

依照下圖,可以直接下載官方所提供的 CSS:

範例 1:直接加上相關 class 套用

  • 在想要套用效果的元素上,加上這 animate__animated 個 class。

  • 然後再加上想套用哪種效果的 class,例如 swing ,就再加上 animate__swing 是不是會有效:

試著套上 heartBeat、fadeIn 動畫效果。

範例 2:沿續上例,效果永久的反覆執行

只要加上 animate__infinite 這個 class 即可。

範例 3:自定義相關屬性

例如:

  • animation-duration:在外掛的官方定義中,預設是 1 秒

  • animation-delay:在外掛的官方定義中,預設是 0 秒

  • animation-iteration-count:在外掛的官方定義中,預設是 1 次

範例 4:透過 JS,動態的加上動畫效果相關 class

有的時候動畫效果樣式,是在使用者做了某種行為之後,才觸發動畫效果。

例如以下範例:使用者點擊按鈕,觸發動畫效果的執行:

動畫效果只會觸發 1 次?

jQuery CDN:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

範例 5:讓動畫效果,透過按鈕可以執行多次

利用官方提供的函式:(不需要瞭解這個函式裡的程式細節,只需要知道怎麼用這個函式即可)

const animateCSS = (element, animation, prefix = 'animate__') =>
  // We create a Promise and return it
  new Promise((resolve, reject) => {
    const animationName = `${prefix}${animation}`;
    const node = document.querySelector(element);

    node.classList.add(`${prefix}animated`, animationName);

    // When the animation ends, we clean the classes and resolve the Promise
    function handleAnimationEnd(event) {
      event.stopPropagation();
      node.classList.remove(`${prefix}animated`, animationName);
      resolve('Animation ended');
    }

    node.addEventListener('animationend', handleAnimationEnd, {once: true});
  });

函式說明:

animateCSS('.the_block', 'bounce');
  1. .the_block 這個元素上,加上 animate__bounce 這個 class(同時也會加上 animate__animated 這個 class)。

  2. 效果執行完後,會自動移除 animate__animatedanimate__bounce 這兩個 class。

範例 6:沿續上例,動畫效果執行完畢後,再執行自己定義的 JS 程式

只要在 animateCSS() 後面,再加上相關的程式即可:

animateCSS('.the_block', 'bounce').then((message) => {
  alert("執行自定義的程式");
});

Last updated