スクロール位置によって背景色を変えたい

実現したいこと

下にスクロールしても上にスクロールしても指定した場所の時にはその背景色になるようにしたい。

発生している問題・分からないこと

・スクロール位置に応じてshowを付与して背景色を変化しているのですが、
赤色の背景になる位置だけなぜか青背景位置にもshowが付き、二か所についている。

・一番上にいるときは、背景色は白に戻すようにしたいのに、一度スクロールしてしまうと、白背景に戻らなくなる。

エラーメッセージ

error

1Consoleエラーメッセージは出ていません。

該当のソースコード

HTML

1 <div class="content__wrap"> 2 <p>背景なし背景なし背景なし背景なし背景なし背景なし</p> 3</div> 4<div class="content__wrap content-wrap--bg content-wrap--bg001"> 5 <p>赤色背景赤色背景赤色背景赤色背景赤色背景赤色背景</p> 6</div> 7 8<div class="content__wrap content-wrap--bg content-wrap--bg002"> 9 <p>青色背景青色背景青色背景青色背景青色背景青色背景</p> 10</div> 11<div class="content__wrap content-wrap--bg content-wrap--bg003"> 12 <p>黄色背景黄色背景黄色背景黄色背景黄色背景黄色背景</p> 13</div>

CSS

1.content__wrap {2 display: flex;3 justify-content: center;4 align-items: center;5 width: 100%;6 height: 100vh;7}8.content__wrap p {9 padding: 50px;10 position: relative;11 z-index: 20;12}13.content-wrap--bg p {14 color: #fff;15}16.content-wrap--bg::before {17 content: "";18 position: fixed;19 top: 0;20 left: 0;21 width: 100%;22 height: 100%;23 background-position: center center;24 background-size: cover;25 background-repeat: no-repeat;26 opacity: 0;27 transition: all 0.5s ease 0s;28 z-index: 0;29}30.content-wrap--bg.show::before {31 opacity: 1;32}33.content-wrap--bg001::before {34 background: #7b0000;35}36 37.content-wrap--bg002::before {38 background: #00147b;39}40.content-wrap--bg003::before {41 background: #957e00;42}

js

1$(function(){2 const showClass = "show"; 3 4 $(".content-wrap--bg").each(function(index, content){5 $(window).on("load scroll resize", function(){6 const windowHeight = $(window).height();7 const scroll = $(window).scrollTop();8 const offset = $(content).offset().top;9 const setTiming = windowHeight * 0.5;10 const contentHeight = $(content).height();11 const outTiming = windowHeight * 0.6;12 13 if (scroll + windowHeight >= offset + setTiming && scroll + windowHeight < offset + contentHeight + outTiming){14 $(content).addClass(showClass);15 } else {16 $(content).removeClass(showClass);17 }18 });19 });20});

試したこと・調べたこと

上記の詳細・結果

jsをチェックしましたが、どこがおかしいのかエラーを見つけられませんでした。
同じようなjsを作っている人と違うを見比べましたが、解決できませんでした。

補足

特になし

コメントを投稿

0 コメント