添加类不工作

addClass is not working

我正在制作一个导航栏,以便当用户滚动到某个点时,导航栏的样式会发生变化。为此,我在用户滚动经过 "changePoint" 的事件上添加了一个 class。出于某种原因,添加的 class 不会改变外观(如果添加的话)。我知道一个事实,条件 if (top > changePoint){ 是 运行 的意思。

java 脚本:

 $(window).on('scroll', function () {
    //top of the screen
    var top = Math.round($(window).scrollTop());

    //if past changePoint, change the style
    if (top > changePoint) {
        $(".navtop").addClass('changeStyle');
        //  window.alert('.navtop');
    } else {
        $('.navtop').removeClass('changeStyle');
    }
});

css:

.topnav {
font-family: 'Montserrat', sans-serif;
font-size: 16px;
margin: 20px;
background-color: transparent;
color: #fff;
transition: all 0.25s ease;
position: fixed;
top: 0;
width: 100%;
padding: 1em 0;
}

.topnav.changeStyle {
background-color: white;
color: #19CEC4;
}

html:

<!--navbar-->
<nav class="topnav">
    <img id=logo src="img/logo-big.svg" height="50px">
    <a href="#">Home</a>
    <a href="#">Events</a>
    <a href="#">About</a>
    <a href="#">Volunteer</a>
    <a href="#">Contact</a>
</nav>

<section id="home">
    <div class="jumbotron" id="jumbotronImg">
        <div class=container>
            <h1>Hi there!</h1>
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed consequat nibh ut fringilla imperdiet. Suspendisse potenti. Sed suscipit interdum ante eget ornare. Donec porttitor eros quam, eget fermentum neque sodales vel. Aenean fringilla id nisl nec finibus. Vivamus elementum lorem a mattis efficitur. </p>
        </div>
    </div>
</section>

在您给出的 jquery 选择器中

$(".navtop");

但是在 css 你正在使用

.topnav

我不清楚您是否在此处输入错误,或者您在脚本中做同样的事情,因为我没有看到您的 html。

针对您的问题,您添加的 css 将尝试将此样式添加到具有 .changestyle class 的元素(子)中,该元素(父)中具有 .topnav class

.topnav.changeStyle { background-color: white; color: #19CEC4; }

只需添加这个

.changeStyle { background-color: white; color: #19CEC4; }

这会将此样式添加到具有此 class

的任何元素