実現したいこと
全画面スクロールのサイトを以下のコードで作りました。ページの一番下にあるtopのボタンを押してページトップにスクロールできるようにしたいのですが、mainにかけているheight100vhがあることにより動作しないです。
html
1 <main class="main"> 2 3 <section class="works"></section> 4 <section class="works works-black"></section> 5 <section class="works works-blue"></section> 6 <section class="works works-green"> </section> 7 <div class="page-top"> 8 <button class="page-top-circle" id="page-top">Top</button> 9 </div> 10 </main> 11
CSS
1body { 2 background-color: #efefef; 3} 4 5main { 6 width: 100%; 7 height: 100vh; 8 overflow-y: scroll; 9 scroll-snap-type: y mandatory; 10 overflow: auto; 11} 12 13.works { 14 height: 100vh; 15 scroll-snap-align: start; 16} 17 18.works-top { 19 background-color: grey; 20} 21 22.works-black { 23 background-color: black; 24} 25 26.works-green { 27 background-color: green; 28} 29 30.works-blue { 31 background-color: blue; 32} 33 34.page-top { 35 scroll-snap-align: start; 36 height: 100vh; 37 display: flex; 38 justify-content: center; 39 align-items: center; 40} 41.page-top .page-top-circle { 42 width: 160px; 43 height: 80px; 44 line-height: 160px; 45 color: #000; 46 font-size: 40px; 47 display: flex; 48 justify-content: center; 49 align-items: center; 50} 51.page-top .page-top-circle:hover { 52 opacity: 0.5; 53}
JavaScript
1const pageTopButton = document.getElementById('page-top'); 2 3pageTopButton.addEventListener('click', () => { 4 window.scrollTo({ 5 top: 0, 6 behavior: 'smooth' 7 }); 8});
試したこと
以下のコードを追加してボタンを押したらmainのheightを解除して1秒後に再び100vhをつけるというパターンを試しました。ですがこれだとスムーススクロールされないのと、ボタンの位置まで戻ってしまいます。
JavaScript
1const mainElement = document.querySelector('main'); 2const buttonElement = document.querySelector('#page-top'); 3 4buttonElement.addEventListener('click', () => { 5 mainElement.style.height = 'auto'; 6 7 setTimeout(() => { 8 mainElement.style.height = '100vh'; 9 }, 1000); 10});
対処法や別の考え方があればご教示のほどよろしくお願いいたします。

回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2023/05/15 11:06