如何使透明导航栏在滚动后具有背景色



我想让导航栏一开始是透明的,但滚动时会有黑色背景色。我知道Javascript最适合这份工作,但我尝试过window.addEventListener,但一直没有成功。任何提示都将不胜感激。

<script>
window.addEventListener( 'scroll', function () {
let nav = document.querySelector('nav');
nav.classList.toggle('scrolling-active');
});
</script>
#header {
height: 100vh;
}
#header nav {
display: flex;
background-color: transparent;
justify-content: space-between;
position: fixed;
width: 100vw;
}

#header nav .name {
display: flex;
width: fit-content;
color: white;
padding-left: 30px;
align-items: center;
font-size: 30px;
}
#header nav .name span {
color: rgb(182, 18, 18);
}
#header nav ul {
display: flex;
list-style: none;
width: fit-content;
}
#header nav ul li {
padding: 30px;
}
#header nav ul li a {
text-decoration: none;
font-size: 25px;
color: white;
font-family: "Yanone Kaffeesatz", sans-serif;
}
.scrolling-active {
background-color: black;
}
<header id="header">
<section class="hero">
<nav class="nav">
<div class="name"><h1><span>D</span>ave <span>A</span>nthony</h1></div>
<ul>
<li><a href="#">Home</a></li>
<li><a href="#">About</a></li>
<li><a href="#">Recent Posts</a></li>
</ul>
</nav>

这归结为CSS的特殊性。你的css中有这个:

#header nav {
display: flex;
background-color: transparent;
justify-content: space-between;
position: fixed;
width: 100vw;
}

id比类更具体,具有更高的重要性,因此它将使用透明的背景色。解决这个问题的一种方法是在添加的类中添加!important子句:

.scrolling-active {
background-color: black !important;
}

然而,这不是最好的方法,因为如果你只是简单地修改你的ID使用,它并不真正需要它(但它会起作用(。

最新更新