LoginSignup
18
16

More than 5 years have passed since last update.

jQuery スクロールに合わせ画像表示(eachで複数一括設定)

Last updated at Posted at 2016-06-22

🍺🍺🍺
はてなブログはじめました。
http://sudara-bluse.hatenablog.com/entry/2017/10/27/013435
🍺🍺🍺

画面を下にスクロールしていくと、
ちょうど良いところでふわっと要素が表示されるよくあるやつ。

いちいち一つ一つ

hoge.js
// スクロール値が400超えたらfadeIn
if($(window).scrollTop() > 400){
  $("#img").fadeIn();
}

のように指定するのは大変なので、
eachを使って、良い感じのとこでfadeInする一括指定コードメモ。

hoge.js
// ターゲットを非表示にしとく
$(".target").css("visibility","hidden").css("opacity","0");

// .targetのついた画像をスクロールに合わせfadeIn
$(window).on("load scroll resize", function(){
    $(".target").each(function(){
        var imgPos = $(this).offset().top;
        var scroll = $(window).scrollTop();
        var windowHeight = $(window).height();
        if (scroll > imgPos - windowHeight + windowHeight / 5){
            // ここに処理を書く
            $(this).css("visibility","visible")
            $(this).animate({opacity: 1}, 300);  
        }
    });
});

便利

18
16
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
18
16