[英]How can I remove the active class from a li?
我的導航欄有問題。 我只需要從li
刪除活動類,在滾動時將此類放到第二個li
,這里是代碼:
$(window).scroll(function () {
if ($(this).scrollTop() >= 650) {
$('#about').addClass("active");
} else {
$('#home').removeClass("active");
}
});
你可以removeClass()
用於#home
ID而addClass()
為#about
元素,反之亦然。 因此,以下代碼將起作用:
$(window).scroll(function() {
if ($(this).scrollTop() >= 650) {
$('#about').addClass("active");
$('#home').removeClass("active");
} else {
$('#about').removeClass("active");
$('#home').addClass("active");
}
});
工作演示
$(window).scroll(function () { if ($(this).scrollTop() >= 650) { $('#about').addClass("active"); $('#home').removeClass("active"); } else { $('#about').removeClass("active"); $('#home').addClass("active"); } });
.fixed{ position : fixed; top: 0; left:0; right:0; } .long{ height : 5000px; } .active{ background : red; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="fixed"> <div id="home" class="active">Home</div> <div id="about">About</div> </div> <div class="long"></div>
根據你認為不夠詳細的問題,讓我們來看看你的代碼“
$(window).scroll(function () {
if ($(this).scrollTop() >= 650) {
$('#about').addClass("active");
//This is when you add class active, but you have to remove class active
//from #about as well
} else {
$('#home').removeClass("active");
//Same thing here, you have to remove class active from #about
}
});
如果你不從另一個元素中刪除活動類,在向上和向下滾動之后你最終會在兩個元素中激活類。 希望我正確地閱讀你的問題並回答你的問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.