|CSS|Keep Menu in View with Sticky CSS

Keep Menu in View with Sticky CSS

若要讓選單在滾動到視窗頂端時脫離原位置並固定於頁面頂端,可使用 position:sticky,就能輕鬆實現選單始終保持在畫面視野中。

這次範例 html 結構,選單放在版頭和內容之間。

html

在 nav 上設置 position:sticky 和 top:0,即可實現選單在滾動到視窗頂端時自動固定在頁面頂端的效果。

css
nav{ position: sticky; top: 0; }  

為了讓選單固定在網頁頂端時能動態展開並與視窗同寬,可以在 nav::before、nav.sticky::before 中加入以下 CSS,讓選單超出父層的寬度。

css
nav::before{  content: "";
              width: 100%; height: 100%;
              position: absolute; top: 0; left: 0;
              z-index: -2;
              background-color: rgba(0, 0, 0, 1);
              transform: scaleX(1);
              transform-origin: center;
              transition: transform 0.8s ease-in-out;
            }            
nav.sticky::before{ transform: scaleX(3); /* 用 scaleX 讓選單超出父層的寬度 */
                    transition: transform 0.8s ease-in-out;
                  }  

然後需用 js 來判斷 nav 位置來添加/移除 sticky。

script
document.addEventListener('DOMContentLoaded', function () {
            const sidebarElement = document.querySelector('nav'); /*  獲取 nav 元素 */
            const sidebarOffsetTop = sidebarElement.offsetTop; /* 獲取元素距離頂部的位置*/

            /* 當滾動時觸發 */
            window.addEventListener('scroll', function () {
                /* 取得滾動的垂直距離 */
                const scrollY = window.scrollY;

                if (scrollY > sidebarOffsetTop) {
                    /* 當滾動超過元素頂部時,添加 class */
                    sidebarElement.classList.add('sticky');
                } else {
                    /* 當滾回元素頂部時,移除 class */
                    sidebarElement.classList.remove('sticky');
                }
            });
});

圖素來源:
AIPICT(https://aipict.com/