导航栏位于页面顶部时的颜色不同

Different Nav Bar Color when it is at the top of Page

本文关键字:颜色 顶部 于页面 导航      更新时间:2023-09-26

我这里有我的HTML导航栏。它目前以白色背景着色,并在我滚动时固定在页面顶部。但是,我希望它最初是透明的/仅在页面顶部时才保持透明,然后在向下滚动时变为白色背景。我应该如何在 JQuery 中实现这一点?

        <header id="header" class="alt">
            <h1><a href="index.html">Company Namez</a></h1>
            <a href="#one">Features</a>
            <a href="#two">About us</a>
            <a href="#three">Team</a>
            <a href="#four">Contact Us</a>
        </header>
你可以

通过添加jquery addClass()和removeClass()来实现,看看下面的代码。

$(document).scroll(function() { 
   if($(window).scrollTop() != 0) {
     $('#header').addClass("navBgcolor");
   }
   else {
   	 $('header').removeClass("navBgcolor");
   }
});
header#header{
  margin: auto;
  text-align:center;
  position: fixed;
  width: 100%;
}
div.content{
  height : 500px;
}
.navBgcolor{
  background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<header id="header" class="alt">
  <h1><a href="index.html">Company Namez</a></h1>
  <a href="#one">Features</a>
  <a href="#two">About us</a>
  <a href="#three">Team</a>
  <a href="#four">Contact Us</a>
</header>
<div class="content"></div>

https://jsfiddle.net/tdmr4gt9/

$(document).scroll(function() { 
   if($(window).scrollTop() === 0) {
     $('header').css("background-color", "rgba(255, 255, 255, 0)")
   }
   else {
     $('header').css("background-color", "rgba(255, 255, 255, 1)")
   }
});