2020年11月12日木曜日

スクロール時に指定した要素をアニメーション付きで表示

ページのスクロール時に、指定した要素を、指定したアニメーションで表示する。

デモページを表示

CSS

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
*[data-scroll-animation] {  /* あらかじめ対象を透明(見えない状態)にしておく */
    opacity: 0;
}
 
/* slideInRight */
.slideInRight {  /* http://anicollection.github.io/#/sliding_entrances/slideInRight */
  animation-duration: 1s;
  animation-fill-mode: both;
  animation-name: slideInRight
}
 
@keyframes slideInRight {
  0% {
    transform: translate3d(100%, 0, 0);
    visibility: visible
  }
  100% {
    transform: translate3d(0, 0, 0)
  }
}
 
/* slideInLeft */
.slideInLeft {  /* http://anicollection.github.io/#/sliding_entrances/slideInLeft */
  animation-duration: 1s;
  animation-fill-mode: both;
  animation-name: slideInLeft
}
 
@keyframes slideInLeft {
  0% {
    transform: translate3d(-100%, 0, 0);
    visibility: visible
  }
  100% {
    transform: translate3d(0, 0, 0)
  }
}
補足
  • アニメーション表示する要素( data-scroll-animation 属性を付けた要素)をあらかじめ透明(見えない状態)にしておく。
  • 設定するアニメーションのクラス( slideInLeft, slideInRight )を用意しておく。
  • レイアウトが崩れる場合は リセットCSS・共通CSS の内容を確認。

jQuery

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
$(function(){
 
  $(window).on('load scroll', function (){
    var target = $('*[data-scroll-animation]');
    target.each(function(){
      var animation = $(this).attr('data-scroll-animation');
      var target_top = $(this).offset().top;
      var window_top = $(window).scrollTop();
      var window_height = $(window).height();
      var bottom_pos = window_height / 4;
      if ( window_top > target_top - window_height + bottom_pos ) {
        $(this).css('opacity', 1);
        $(this).addClass(animation);
      }
    });
  });
 
});
補足
  • このサンプルでは、対象となる各要素( data-scroll-animation 属性を付けた要素)の上端が、ウィンドウ高さの1/4を超えたらアニメーションが始まり、表示される。
  • アニメーション表示されるのは、最初に表示される時だけ。
  • デモページで使用している jQuery のバージョンは 1.12.4 。

HTML

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<ul>
  <li data-scroll-animation="slideInLeft">
    <img alt="画像" src="./files/image-01.jpg" />
  </li>
  <li data-scroll-animation="slideInRight">
    <img alt="画像" src="./files/image-02.jpg" />
  </li>
  <li data-scroll-animation="slideInLeft">
    <img alt="画像" src="./files/image-03.jpg" />
  </li>
  <li data-scroll-animation="slideInRight">
    <img alt="画像" src="./files/image-04.jpg" />
  </li>
</ul>
補足
  • アニメーション表示する要素に data-scroll-animation 属性とアニメーションを定義したクラスを設定する。

関連投稿