twitter-bootstrap 如何从 Bootstrap 3.1 中的导航栏链接中删除活动类?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23082303/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 20:30:42  来源:igfitidea点击:

How to remove active class from navbar links in Bootstrap 3.1?

jquerycsstwitter-bootstraptwitter-bootstrap-3navbar

提问by Loolooii

I am using one page navigation and I don't know how to remove the active state from the lielement when I am in that particular section of the page. I have tried using JQuery and CSS and none works for me (from the console it works obviously).

我正在使用单页导航,li当我处于页面的特定部分时,我不知道如何从元素中删除活动状态。我曾尝试使用 JQuery 和 CSS,但没有一个对我有用(从控制台它显然有效)。

This is what works in the console:

这是在控制台中的工作:

$('.nav li').removeClass('active');

And in CSS I tried:

在 CSS 中我尝试过:

.nav > li {  
   background: transparent;
}

I prefer a JQuery solution as it would be easier just to get rid of the active class instead of styling the element.

我更喜欢 JQuery 解决方案,因为摆脱活动类而不是为元素设置样式会更容易。

回答by Milind Anantwar

Looks like there are multiple listeners for document ready. And your code is getting executed before other handler/handlers which sets the class active again. You can use e.stopImmediatePropagation()to prevent that. Try this:

看起来文档就绪有多个侦听器。并且您的代码将在其他处理程序/处理程序之前执行,这些处理程序/处理程序再次将类设置为活动状态。你可以用它e.stopImmediatePropagation()来防止。试试这个:

$(document).ready(function(e){
   e.stopImmediatePropagation();
   $('.nav li').removeClass('active');//or $('.active').removeClass('active');
});

Update:

更新:

You can also achieve this using setInterval():

您还可以使用setInterval()以下方法实现:

setInterval(function(){
  $('.active').removeClass('active');//remove class active
},1000);

回答by Billy Moat

In your html just don't have the active class on any li when the page loads - Unless you want to have 'home' or something active by default then of course have the active class on the relevant li.

在您的 html 中,当页面加载时,任何 li 上都没有活动类 - 除非您想要“主页”或默认情况下处于活动状态的东西,否则当然在相关 li 上有活动类。

Then when a user clicks on an li try this:

然后当用户点击 li 时,试试这个:

$(".nav li").click(function() {
    $(".nav li").removeClass('active');
    $(this).addClass('active');    
});

The above will remove the active class from whatever li it is on then add it to the one which has been clicked.

以上将从它所在的任何 li 中删除活动类,然后将其添加到已单击的那个。