Animate.cssを使ってみる

簡易に要素のアニメーションを設定できるCSSのライブラリ「Animate.css」を試してみます。
使用するバージョンは4.1.1になります。

設定方法

今回はCDNを使って読み込みます。

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css" />

あとはアニメーションさせたい要素にclassを設定します。
設定するclass名は「animate__animated」と「animate__アニメーション名」で、アニメーション名部分に動きに応じた値を入れます。
アニメーション名で設定できる内容や動きのサンプルは公式ドキュメントにありますので、そちらをご確認ください。

<h2 class="animate__animated animate__bounce">An animated element</h2>

これでアニメーションの設定ができました。
アニメーションのデモページ

アニメーションのタイミングの遅延やループのclassも用意されています。

<h2 class="animate__animated animate__bounce animate__delay-2s">An animated element</h2>
<h2 class="animate__animated animate__bounce animate__infinite">An animated element</h2>

遅延・ループのデモページ

ライブラリ側で用意されたclassではなく、@keyframesを直接使用することもできます。

<h2 class="sample">An animated element</h2>

アニメーション名と時間を設定します。

.sample {
  display: inline-block; /* 要素が display: inline; の場合は追加する */

  animation-name: bounce;
  animation-duration: 2s;
}

@keyframesを直接使用するデモページ
今回の例では不要ですが、アニメーション要素が display: inline; の場合はアニメーションが行われないため、そういった場合には display: inline-block; を追加する必要があります。

JavaScriptでclassを追加することで、任意のタイミングでアニメーションの実行なども可能です。
例えば、スクロールして要素が画面内に入ったタイミングでアニメーションするようにしてみます。

<div class="contents">
  <section class="section">
    <h2 data-animate="bounce">An animated element</h2>
  </section>
  <section class="section">
    <h2 data-animate="rubberBand">An animated element</h2>
  </section>
  <section class="section">
    <h2 data-animate="swing">An animated element</h2>
  </section>
  <section class="section">
    <h2 data-animate="backInDown">An animated element</h2>
  </section>
  <section class="section">
    <h2 data-animate="lightSpeedInLeft">An animated element</h2>
  </section>
</div>

data-animateが設定されている要素をアニメーションの対象として、その値にアニメーション名を指定しています。
Intersection Observerを使って、該当要素が画面内に入ったら必要なclassを追加するようにします。

document.addEventListener("DOMContentLoaded", function() {
  var animationElements = [].slice.call(document.querySelectorAll('[data-animate]'));
  if("IntersectionObserver" in window) {
    var animationObserver = new IntersectionObserver(function(entries, observer) {
      entries.forEach(function(entry) {
        if (entry.isIntersecting) {
          var target = entry.target;
          target.classList.add('animate__animated', 'animate__' + target.dataset.animate);
          animationObserver.unobserve(target);
        }
      });
    });
    animationElements.forEach(function(animationElement) {
      animationObserver.observe(animationElement);
    });
  }
});

これでスクロールに合わせてアニメーションさせることができました。
スクロールに合わせてアニメーションを実行するデモページ

参考サイト

このエントリーをはてなブックマークに追加

関連記事

コメントを残す

メールアドレスが公開されることはありません。
* が付いている欄は必須項目です

CAPTCHA


コメントが承認されるまで時間がかかります。

2024年4月
 123456
78910111213
14151617181920
21222324252627
282930