LoginSignup
12
14

More than 5 years have passed since last update.

スクロールして表示領域に入ったら要素をアニメーション表示する

Last updated at Posted at 2018-01-03

要素が画面に表示されたタイミングでいい感じにアニメーションして表示させたいときの備忘録。
jsライブラリの「jQuery.inview.js」とアニメーションのCSSライブラリ「animated.css」を使用します。
inviewだけでもアニメーションさせることはできますが、より色んなアニメーションをつけたいとき、違うライブラリに変えてみたり試行錯誤してみましたが、「animatede.css」を併用する方法が一番ラクだったので。。。

使用するライブラリ

jQuery.inview.js
animated.css
(使用する際は各サイトから最新版をCHECK)

ライブラリの読み込み

head内に「animated.css」、body閉じタグ前にjQuery本体と「jQuery.inview.js」を記述。
(animated.cssはCDNあるのでそちらを使用・jQuery本体はGoogleのCDN)

head_sample
<head>
・・・
<link rel="stylesheet" 
href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.5.2/animate.min.css">
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" src="/path/to/js/jquery.inview.min.js"></script>
</body>
</html>

htmlコード

inviewしたい要素に任意のクラス名と、「animated.css」を適用するためのクラス名「animated」を記述。

code_sample
<div class="animated inviewfadeInLeft">
fadeInLeft
</div>

<div class="animated inviewlightSpeedIn">
lightSpeedIn
</div>

<div class="animated inviewslideInLeft">
slideInLeft
</div>

jQueryコード

上記htmlコードの場合のjQueryコード。
アニメーションの動きはanimated.cssから選択。
(addClassでつけているクラス名が「animated.css」のクラス名)

jquery_sample
$(function() {
  $('.inviewfadeInLeft').on('inview', function(event, isInView) {
    if (isInView) {
    //表示領域に入った時
      $(this).addClass('fadeInLeft');
    } else {
    //表示領域から出た時
      $(this).removeClass('fadeInLeft');
      $(this).css('opacity',0); //非表示にしておく
    }
  });
  $('.inviewlightSpeedIn').on('inview', function(event, isInView) {
    if (isInView) {
      $(this).addClass('lightSpeedIn');
    } else {
      $(this).removeClass('lightSpeedIn');
    }
  });
  $('.inviewslideInLeft').on('inview', function(event, isInView) {
    if (isInView) {
      $(this).addClass('slideInLeft');
    } else {
      $(this).removeClass('slideInLeft');
    }
  });
});

inviewのコールバック関数は「isInView」「visiblePartX」「visiblePartY」の3つ。

「isInView」は要素が表示領域に見えるかどうかで「true」か「false」になる。
「visiblePartX」は要素の左右を基準に、「visiblePartY」は要素の上下を基準にする。
「visiblePartX」は、left・right・both、
「visiblePartY」は、top・bottom・both を選択。

基本は「isInView」でOK。

参考

参考にさせていただきました。ありがとうございます。
http://gimmicklog.main.jp/jquery/581/

12
14
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
14