要素を指定位置でフェードイン・アウトさせるには?

実現したいこと

●ボタンを指定の位置でフェードイン・アウトさせたい

前提

●独学でコーデイングの勉強をしています。
わからない事は、ネットで調べ解決していますが、
今回、フェードインまでは出来ましたが、アウトがわかりません。
jQueryは使わず、素のJSで実装しようとしています。

該当のソースコード

HTML

1<div class="container"> 2 <a href="#" id="button">ボタン</a> 3 <h1 id="start">開始場所</h1> 4 <h1 id="end">終了場所</h1> 5</div>

CSS
.container {
height: 2000px;
position: relative;
}

#button {
display: flex;
justify-content: center;
align-items: center;
width: 50px;
height: 50px;
color: #fff;
text-decoration: none;
background: red;
position: fixed;
bottom: 30px;
right: 30px;
opacity: 0;
transform: translateX(80px);
transition: .5s;
}

#button.show {
opacity: 1;
transform: none;
}

h1 {
width: 200px;
height: 70px;
line-height: 70px;
text-align: center;
color: #fff;
position: absolute;
}

#start {
background: green;
top: 800px;
left: 50%;
transform: translateX(-100px);
}

#end {
background: blue;
top: 1500px;
left: 50%;
transform: translateX(-100px);
}

JS
const button = document.getElementById('button');
let startHeight = document.getElementById('start').clientHeight;
let endHeight = document.getElementById('end').clientHeight;

window.addEventListener('scroll', function () {
let scrollTop = window.scrollY || document.documentElement.scrollTop;
if (scrollTop > startHeight) {
button.classList.add('show');
}
else if (scrollTop > endHeight) {
button.classList.remove('show');
} else {
button.classList.remove('show');
}

});

試したこと

他のやり方でも試しましたが、やはりアウトがうまくいきません。
初めて質問しました。
よろしくお願いします。

コメントを投稿

0 コメント