小金井にあるWEB制作会社の備忘録

MEMORANDUM

animate.cssを使ってスクロールアニメーションを簡単に実装する

一般的になってきたスクロールアニメーション。
以前はモーションを一つづつ作成していましたが、複雑な動きで無ければ簡単に実装できる「animate.css」を見つけたので実装方法をメモ。

「animate.css」を使ったスクロールアニメーションの実装方法

animate.cssを読み込む

まずは、Animate.cssのサイトからCDNで提供されている「animate.css」を読み込む

CSS

@import url('https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css');

「animate__animated」クラスを追加

アニメーションを行いたいHTMLタグに「animate__animated」クラスを追加します。

HTML

<section class="animate__animated">
コンテンツ01
</section>

<section class="animate__animated">
コンテンツ02
</section>

<section class="animate__animated">
コンテンツ03
</section>

<section class="animate__animated">
コンテンツ04
</section>

<section class="animate__animated">
コンテンツ05
</section>

<section class="animate__animated">
コンテンツ06
</section>

使いたいアニメーションを探して、「クラス名」をコピー。

サイトの右側のリストからアニメーションが確認できるので、動きを確認したら、すぐ横のアイコンから「クラス名」をコピー。
今回は「animate__fadeInUp」を使用します。

jsファイルを作成してアニメーションを設定。

使用するアニメーションが決定したら、jsファイルを作成して「クラス名」を設定。今回はスクロールアニメーションのソース内に記載します。

jQuery

//スクロールアニメーション
$(window).scroll(function(){
	let sH = window.innerHeight * 7 / 10; //トリガー位置の設定
	let offsetTop = $(window).scrollTop();
	
	if($('.animate__animated').length){
		for (var j = 0; j < $('.animate__animated').length; j++){
			if(offsetTop > $('.animate__animated').eq(j).offset().top - sH){
				if(!$('.animate__animated').eq(j).hasClass('animate__fadeInUp')){
					$('.animate__animated').eq(j).addClass('animate__fadeInUp');
				}
			}
		}
	}

});

「sH」の部分でスクロール量を設置。
「animate__animate」のついているタグを自動でカウントし、スクロール量に達した時点で「animate__fadeInUp」の無いものにクラスに追加(アニメーション発動)しています。

今回のモーションは非表示の状態から表示されるパターンのものなので、CSSも調整する。

CSS

.animate__animated {
	opacity: 0;
}

同一カテゴリーの記事