jQueryでスクロールのたびにアニメーションを使うには、
Waypoints.jsとAnimate.cssという2つのライブラリを併用します。
Waypoints.jsを読み込み
Waypoints.jsはスクロールが一定位置まで来た時に
特定のJavaScriptを実行するためのライブラリです。
Waypoints.jaからdownloadボタンからダウンロード。
libフォルダの中にあるjquery.waypoints.min.jsというファイルだけを
アニメーションを作業中のHTMLと同じディレクトリに格納し読み込みを行う。
<!-- </body>の直前に置く -->
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<!-- jqueryの読み込みの下に記入 -->
<script src="jquery.waypoints.min.js"></script>
jQueryで要素を選択してから.waypoint()を呼び出します。
//box部分が.waypoint()を呼び出す要素
$(".box").waypoint({
handler(direction){
//.boxが画面内に入った時に実行される処理をここに記入
//direction引数には、下方向のスクロール時は"down"
//上スクロール時は"up"
},
//要素が画面の上端がどの位置に来た時にhandlerを実行するのか
//0%なら画面の一番上、50%なら画面の真ん中、100%なら画面の一番下で実行
offset: "50%",
});
Animate.cssを読み込み
Animate.cssはHTM要素にアニメーションクラスを付けるだけで
簡単にアニメーションがつくライブラリです。
Animate.cssから
サイトの「Download Animate.css」を右クリック
→別名で保存し、ダウンロードしたanimate.cssを
作業中のHTMLと同じディレクトリに格納。
そして、HTML内で格納
<!-- <head>内に置く -->
<link rel="stylesheet" href="animate.css">
スクロールの時にアニメーションを出す方法
アニメーションをスクロール時に出すには
Waypoints.jsとAnimate.cssの組み合わせが必要です。
アニメーションを加えたい部分にanimatedクラスと
fadeInUpなど動きのアニメーションのクラスをつける。
(Animate.cssからアニメーションは確認できます)
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>Animate Test</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.7.2/animate.css">
<style>
body {
background: repeating-linear-gradient(0deg,
#ffffff,
#ffffff 40px,
#dedede 40px,
#dedede 80px);
}
.boxes {
margin: 80vh auto;
}
.box {
border: 1px solid #000;
width: 10em;
padding: 10px;
margin: 2em auto;
text-align: center;
}
.animated {
/* 最初から非表示 */
opacity: 0;
}
</style>
</head>
<body>
<div class="boxes">
<div class="box animated">box</div>
<div class="box animated">box</div>
<div class="box animated">box</div>
<div class="box animated">box</div>
<div class="box animated">box</div>
<div class="box animated">box</div>
<div class="box animated">box</div>
<div class="box animated">box</div>
<div class="box animated">box</div>
<div class="box animated">box</div>
</div>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/waypoints/4.0.1/jquery.waypoints.js"></script>
<script src="main.js"></script>
</body>
</html>
今回は、HTML側ではanimatedクラスだけをつけて
jQuery側で下へスクロールをした際にfadeInUpクラスを付けてみます。
//box部分が.waypoint()を呼び出す要素
$(".animated").waypoint({
handler(direction){
if(direction === "down") {
$(this.element).addClass("dadeInUp");
//waypointoを削除することでこれ以降handlerが呼ばれなくなる
this.destroy();
}
},
//画面の一番下に来たらhandlerを実行
offset: "100%",
});
アニメーションの繰り返し
infiniteクラスを追加することでアニメーションが無限にループされ続けます。
<div class="box animated infinite fadeInUp">box</div>
スクロールを繰り返した場合も
アニメーションを繰り返す方法については
jQueryでスクロールのたびにアニメーションを繰り返す方法に書きましたので
参考にしてください。