gpt4 book ai didi

javascript - 粘性 header jQuery addClass 不起作用

转载 作者:行者123 更新时间:2023-11-28 04:16:28 24 4
gpt4 key购买 nike

我正在尝试创建粘性 header ,但是当我向下滚动 jQuery addClass 函数时,我也尝试过使用 $(this) 但它也不起作用。我试图在滚动时添加另一个类,但它不起作用。我想更改标题的背景 color这是我的 HTML 代码

$(document).ready(function() {

$(window).scroll(function() {
var scroll = $(window).scrollTop();
var objectSelect = $(".myNavigation");
var objectPosition = objectSelect.offset().top;
if (scroll > objectPosition) {
$(this).addClass("active");
} else {
$(this).removeClass("active");
}
});


});
.active {
background: #147cc4 !important;
color: #fff !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<nav class="navbar navbar-expand-md fixed-top navbar-dark mb-4 myNavigation">

<div class="container">
<div class="col-md-2">
<ul class="navbar-nav mr-auto">
<form class="form-inline navbar-form" role="search">
<div class="search">

<span class="fa fa-search"></span>

<input type="text" class="form-control" placeholder="Search">

</div>
</form>
</ul>
</div>


<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarCollapse">

<ul class="navbar-nav ml-auto">

<li class="nav-item">
<a class="logoFont">Hifzil</a>
</li>

</ul>

<ul class="navbar-nav ml-auto">

<li class="nav-item">
<a class="nav-link">Donate</a>
</li>

<li class="nav-item">
<a class="nav-link">Login</a>
</li>
<li class="nav-item">
<a class="nav-link">Sign In</a>
</li>
</ul>
</div>
</div>
</nav>

这是我更改背景颜色css

最佳答案

问题:- 在您的情况下,$(this) 指的是 window 而不是 .myNavigation

解决方案:-

$(this).addClass("active");
$(this).removeClass("active");

需要:-

objectSelect.addClass("active");
objectSelect.removeClass("active");

工作片段:- https://jsfiddle.net/7ko4k75t/

关于javascript - 粘性 header jQuery addClass 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47853811/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com