下にスクロールして、指定した要素に辿り着いたら、指定のクラスを追加したいのですが、
何故かページが表示した瞬間にクラスが付いてしまう。
▼以下のanimatedクラスは正常にクラスが付く&消える
.animated01 , .animated02 , .animated03 , .animated04 , .animated05
▼以下のクラスだけ、ページが表示された瞬間にクラス(show)が付いてしまう
.background
このクラスだけ表示される位置を変えているので、if文の書き方がおかしいのでしょうか?
js初心者で解決策が見つかりません。
解決策を教えていただけると幸いです。
js
1$(function(){ 2 $(window).scroll(function (){ 3 $(".animated01 , .animated02 , .animated03 , .animated04 , .animated05 , .background").each(function(){ 4 var imgPos = $(this).offset().top; 5 var scroll = $(window).scrollTop(); 6 var windowHeight = $(window).height(); 7 var flag; 8 var background; 9 10 if($(this).hasClass('animated01')){ 11 flag = 'fade-in-top'; 12 } else if($(this).hasClass('animated02')) { 13 flag = 'fade-in-bottom'; 14 } else if($(this).hasClass('animated03')) { 15 flag = 'fade-in-left'; 16 } else if($(this).hasClass('animated04')) { 17 flag = 'fade-in-right'; 18 } else if($(this).hasClass('animated05')) { 19 flag = 'slit-in-button'; 20 } else { 21 background = 'show'; 22 } 23 24 if (scroll > imgPos - windowHeight){ 25 $(this).addClass(flag); 26 } else { 27 $(this).removeClass(flag); 28 } 29 30 if (scroll > imgPos - windowHeight + 100){ 31 $(this).addClass(background); 32 } else { 33 $(this).removeClass(background); 34 } 35 }); 36 }); 37});
html
1<section> 2 <div class="background"></div> 3 <h2 class="animated01">ああああああああ</h2> 4</section> 5<section> 6 <div class="background"></div> 7 <h2 class="animated02">いいいいい</h2> 8</section> 9<section> 10 <div class="background"></div> 11 <h2 class="animated03">ううううう</h2> 12</section> 13<section> 14 <div class="background"></div> 15 <h2 class="animated04">えええええ</h2> 16</section> 17<section> 18 <div class="background"></div> 19 <h2 class="animated05">おおおおお</h2> 20</section>
css
1.background { 2 top: 0; 3 left: 0; 4 right: 0; 5 height: 100%; 6 position: fixed; 7 background-position: center center; 8 opacity: 0; 9 -webkit-background-size: cover; 10 background-size: cover; 11 -webkit-transition: all 0.5s ease 0s; 12 -moz-transition: all 0.5s ease 0s; 13 transition: all 0.5s ease 0s; 14 z-index: -1; 15 background-image: url("aaa.jpg"); 16} 17.background.show { 18 opacity: 1; 19}
回答3件
あなたの回答
tips
プレビュー