Sticky Nav


Posted by wayne201299 on 2023-10-03

DEMO

將Nav置頂

實作

  1. 當視窗滾輪向下滑動的距離window.scrollY大於nav與視窗最頂的距離nav.offsetHeight,我們要把nav置頂,透過監聽scroll來得知目前捲軸狀態

     const nav = document.querySelector("#main");
     const topOfNav = nav.offsetTop;
    
     function fixNav() {
         if (window.scrollY >= topOfNav) {
             document.body.style.paddingTop = nav.offsetHeight + "px";
             document.body.classList.add("fixed-nav");
         } else {
             document.body.style.paddingTop = 0;
             document.body.classList.remove("fixed-nav");
         }
     }
    
     window.addEventListener("scroll", fixNav);
    

    function fixNav()內的topOfNav換成nav.offsetTop會導致抓到的nav.offsetTop因為fixed了,所以都會是0,永遠無法把fixed-nav的class清除掉,推測應該是function作用域的影響

  2. 置頂CSS

     .fixed-nav nav {
         position: fixed;
         box-shadow: 0 5px rgba(0, 0, 0, 0.1);
     }
    
     .fixed-nav li.logo {
         max-width: 500px;
     }
    
     .fixed-nav .site-wrap {
         transform: scale(1);
     }
    

    transition效果需要在起始跟結束的屬性都有值的情況下才會起作用

知識點

  • position:fixed的element在HTML DOM中不占位置,之後的element會自動向前補齊

#javascript #css







Related Posts

Day07 - 網格排版

Day07 - 網格排版

簡介 Markov Decision Process 與其應用

簡介 Markov Decision Process 與其應用

Customizing a Laptop Through Engraving is a Great Personalization Idea

Customizing a Laptop Through Engraving is a Great Personalization Idea


Comments