簡體   English   中英

100vh 后在滾動時更改導航欄顏色

[英]Changing navbar color on scroll after 100vh

當我滾動超過 100vh 時(當我從一個部分更改為另一個部分時),我想更改導航欄的顏色。 我怎樣才能做到這一點? 我測試了這段代碼,但它不起作用。

const myNav = document.getElementById('header');
window.onscroll = function () { 
    "use strict";
    if (document.body.scrollTop > document.height ) {
        myNav.classList.add("scrolled");
    } 
    else {;
        myNav.classList.remove("scrolled");
    }
};

這是CSS:

header {
    position: fixed;
    left: 0;
    top: 0;
    right: 0;
    transition: 0.2s;
    z-index: 1000;
    display: flex;
    justify-content: center;
}

.scrolled {
    background-color: black;
    z-index: 1;
    
}

要獲得滾動位置使用window.scrollY並獲得 veiwport 高度使用window.innerheight這樣做:

 const myNav = document.getElementById('header') window.onscroll = function() { if(window.scrollY > window.innerHeight){ myNav.classList.add('scrolled') }else{ myNav.classList.remove('scrolled') } }
 body{ min-height: 400vh; } nav{ position:fixed; top: 0; left: 0; height: 50px; width: 100%; background: green; } nav.scrolled{ background: black; }
 <nav id="header"></nav>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM