スクロール – js –

JS

今回はスクロールについてです。

スクロールしたらアニメーションさせる、

スクロールしたらナビゲーションを表示させる、

などスクロールを使う時のjsについてメモです。

スクロール量を取得

scrollTop();

$(function() {
$(window).on('scroll', function(){
  let scroll = $(this).scrollTop();
  console.log(scroll);
 });
});

画面上部から要素の終わりまでの距離を取得

offset().top

html要素、ここでは画面上部から.conまでの距離を取得

$(function() {
 $(window).on('scroll', function(){
   let scroll = $(".con").offset().top;
   console.log(scroll);
 });
});

スクロールアップ時にヘッダーを表示

$(function() {
    let prevScrollpos = window.pageYOffset;
      let header = document.getElementById("header");

      window.onscroll = function () {
        let currentScrollPos = window.pageYOffset;

        if (prevScrollpos > currentScrollPos) {
          header.style.top = "0"; // スクロールアップ時にヘッダーを表示
        } else {
          header.style.top = "-110px"; // スクロールダウン時にヘッダーを隠す
        }
        prevScrollpos = currentScrollPos;// 現在のスクロール位置を次回の比較用に記録
      };
});

スクロールするとふわっとアニメーションさせる

ふわっとアニメーションさせたい要素(ここでは.animation)の画面上部からの距離から要素の高さを引いた高さがスクロール量を超えたらactiveクラスを付与します。ここではheight/100を足しています。お好みで調節してください。

$(function(){
		$(window).on('load scroll',function (){
			$('.animation').each(function(){
				let target = $(this).offset().top;
				let scroll = $(window).scrollTop();
				let height = $(window).height();
				if (scroll > target - height + height/100){
					$(this).addClass('active');
				}
                                else {
				        $(this).removeClass('active');
				}
			});
		});
	});

アニメーション

activeクラスがついた要素(.animation)の中の要素(.circle)をアニメーション(今回はバウンド)をさせる場合。

activeクラスがついたらopacity: 1;で表示させます。

.animation .circle {
   opacity: 0;
   animation: .5s bound ease-in infinite alternate;
}

.animation.active .circle {
   opacity: 1;
}

@keyframes bound{
	 0%{transform:translateY(0px);}
	 100%{transform: translateY(24px);}
}