我正在制作一个导航栏,以便当用户滚动到某个点时,导航栏的样式会发生变化。为此,我在用户滚动经过“changePoint”的事件上添加了一个类。由于某种原因,添加的类不会改变外观(如果甚至添加的话)。我知道一个事实,条件 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 类的元素(子)中,该元素(父)具有 .topnav 类
.topnav.changeStyle {
背景色:白色;
颜色:#19CEC4;
}
只需添加这个
.changeStyle {
背景色:白色;
颜色:#19CEC4;
}
这会将此样式添加到具有此类的任何元素
关于javascript - 添加类不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39187976/