実現したいこと
以下のページで行われているサイドバーの動きをそっくり実装したいです。
https://www.marketenterprise.co.jp/journal
以下のようなhtmlで、
サイドバーには
- 100vhより大きいheight
- サイドバーの上端または下端までスクロールしたらその場所で固定
を適用させたいです。
(説明より見ていただいた方が早いです)
HTML
1<div class="container"> 2 3 <div class="main"> 4 <!-- サイドバーよりも多いコンテンツ量 --> 5 〜〜〜 6 </div> 7 8 <div class="side"> 9 <!-- 100vhを超えるコンテンツ量 --> 10 〜〜〜 11 </div> 12 13</div>
CSS
1.container { 2 display: flex; 3}
発生している問題
- 100vhより大きいサイドバーにposition: stickyを当ててもtopかbottomどちらかにしか固定されない
- 元のソースではスクロール量に応じてposition:fixedとabsoluteを切り替えているようだが、どのタイミングでどんな切り替えを行っているのか不明
試したこと
- JavaScriptで、スクロール量に応じてサイドバーをfixedまたはabsoluteさせるclassを付与しようとしましたが、absoluteの時に当てたtopの値がfixedでも残ってしまいます
JavaScript
1 const el_main = document.querySelector(".main); 2 const el_side = document.querySelector(".side"); 3 const height_window = window.innerHeight; 4 5 let dfrTop = 0; 6 let scrollNow = 0; 7 let scrollPrev = 0; 8 9 window.addEventListener("scroll", function () { 10 11 // スクロール量取得 12 scrollNow = window.scrollY; 13 14 if (el_main.getBoundingClientRect().top < 0 && 15 el_main.getBoundingClientRect().bottom > height_window) { 16 17 // absoluteの時に当てたいtopの量 18 dfrTop = el_main.getBoundingClientRect().top - el_side.getBoundingClientRect().top; 19 if (dfrTop < 0) { 20 dfrTop = dfrTop * -1 21 } 22 23 if (scrollNow > scrollPrev) { 24 // 下スクロール 25 26 if (el_side.getBoundingClientRect().bottom < height_window) { 27 el_side.classList.remove("fixed_top"); 28 el_side.classList.remove("absolute"); 29 el_side.classList.add("fixed_bottom"); 30 31 } else { 32 el_side.classList.remove("fixed_top"); 33 el_side.classList.remove("fixed_bottom"); 34 el_side.classList.add("absolute"); 35 el_side.style.top = dfrTop + "px"; 36 } 37 38 } else { 39 // 上スクロール 40 41 if (el_side.getBoundingClientRect().top > height_header) { 42 el_side.classList.remove("fixed_bottom"); 43 el_side.classList.remove("absolute"); 44 el_side.classList.add("fixed_top"); 45 46 } else { 47 el_side.classList.remove("fixed_top"); 48 el_side.classList.remove("fixed_bottom"); 49 el_side.classList.add("absolute"); 50 el_side.style.top = dfrTop + "px"; 51 } 52 53 } 54 55 } else { 56 el_side.classList.remove("fixed_top"); 57 el_side.classList.remove("fixed_bottom"); 58 el_side.classList.add("absolute"); 59 el_side.style.top = dfrTop + "px"; 60 } 61 62 scrollPrev = scrollNow; 63 64 }); 65

バッドをするには、ログインかつ
こちらの条件を満たす必要があります。