[英]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.