我的JQuery或其他我不知道的东西有问题。我正在尝试使导航栏将颜色从白色更改为半透明黑色。如果我在错误的地方放置了文字或完全添加了错误的文字,有人可以帮我解释我做错了什么吗?我现在只有12年级,所以我是一个菜鸟。另外,这是针对学校项目的。



$(window).on('scroll',function(){
    if($(window).scrollTop()){
        $('nav').addClass('black');
    }
    else{
        $('nav').removeClass('black');
    }
})

*{
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}
body{
    font-size: 10px;
    font-family:'Raleway', sans-serif;
}
nav{
    background-color: white;
    position: fixed;
    width: 100%;
    height: 2.5rem;
    padding-top: 1rem;
    padding-bottom: 1rem;
    z-index: 5;

    box-shadow: 0 .1rem .3rem rgba(0, 0, 0, 0.247);
}
nav ul{
    position: absolute;
    top:50%;
    left: 50%;
    transform: translate(-50%, -50%);
    list-style: none;
    white-space: nowrap;
}
nav li{
    display: inline;
    padding: 2rem;
    font-size: 1rem;
    text-transform: uppercase;
    font-weight: bolder;
}
a:link{
    text-decoration: none;
    color: black;
    transition: .3s ease-in-out;
}
a:visited{
    text-decoration: none;
    color: black;
}
a:hover{
    color: rgb(161, 161, 161);
}
nav .black{
    background-color: rgba(0, 0, 0, 0.856);
}
nav .black ul li a{
    color: white;
}

<head>
        <link rel="stylesheet" href="style.css">
        <link href="https://fonts.googleapis.com/css?family=Raleway" rel="stylesheet">
        <link href="https://fonts.googleapis.com/css?family=Neucha" rel="stylesheet">
        <link rel="shortcut icon" type="image/png" href="img/logo.png">
        <title>Cole Coffee - One stop shop to suite all your coffee bean needs</title>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    </head>
   <body>
   <nav>
      <ul>
       <li><a href="#our-products">Products</a></li>
       <li><a href="about.html" class="about-tab">About Us</a></li>
       <li><a href="contact.html" class="contact-tab">Contact Us</a></li>
      </ul>
   </nav>
   <!--The rest of my webpage goes here-->

最佳答案

在CSS中,您有一个选择器,例如nav .black。这将选择所有带有“ black”类的nav元素的后代。如果将其替换为nav.black,则可以使用“黑色”类选择所有导航元素,因此应应用样式。

编辑:顺便说一句,我想您已经了解了这一部分,但是如果您进行了上述更改,并且“半透明黑色”在您期望的时间仍然不总是适用,请参见https://api.jquery.com/scrollTop/


  如果滚动条在最顶部,或者元素不在
  滚动,该数字将为0。


并注意if(0)的值为false

07-28 02:30
查看更多