问题描述
你好,我有一个来自引导程序的导航栏,我想在自动切换页面时添加活动类.
hello i have a navbar from bootstap and i want to add class avtive when i switch page automativly.
如何做到这一点.我有我的脚本,但无法正常工作.
how to do that. i have my script but it wont work.
如何使用jquery做到这一点?
how to do that with jquery?
<nav class="navbar navbar-default navbar-inverse navbar-fixed-top">
<div class="container">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">
<img src="img/logogram.png" alt="">
</a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav">
<li class="active"><a href="people.html">people</a></li>
<li><a href="#">gallery</a></li>
<li><a href="inspiration.html">inspiration</a></li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li><a href="timeline-job.html">Jobs oportunity</a></li>
<li><a href="#">hirring a chief?</a></li>
<li><a href="register-1.html">login|signup</a></li>
</ul>
</div><!-- /.navbar-collapse -->
</div><!-- /.container-fluid -->
</nav>
<script>
var loc = window.location.href;
$('.navbar ul li a').each(function () {
var status = loc.indexOf($(this).attr('href')) > -1;
// $(this).toggleClass('active', status);
if (status) {
$(this).addClass('active');
}
});
</script>
请帮助,我不知道为什么我的查询不起作用
please help, i dont know why my query didnt work
推荐答案
因此,您很容易为.navbar ul li a
运行每个函数来检查window.location.href
是否等于navbar href.然后添加活动类.
So this is fairly easy you run an each function for your .navbar ul li a
to check if the window.location.href
equals the navbar href. Then you add the active class.
在引导程序中,您希望将活动类添加到导航栏<li>
标签而不是<a>
标签,因此在以下示例中,我将活动类添加到了<a>
的父级,但是如果原因是您不希望它添加到li中,然后从脚本中删除.parent()
,它将把它添加到<a>
标记中.另外,您不需要手动将活动类添加到第一个<li>
标记中,因为脚本将为您完成此操作,因此您可以从导航栏<li>
标记中删除所有活动类.所有这些,您的jquery脚本将非常简单地如下所示:
In bootstrap you want the active class to be added to the navbars <li>
tag and not the <a>
tag so in the following example I have added the active class to the parent of the <a>
but if for some reason you don't want it to add to the li then remove the .parent()
from the script and it will add it to the <a>
tag. Also you don't need to manually add the active class to the first <li>
tag because the script will do it for you so you can remove all active classes from you navbars <li>
tags. All that being said your jquery script will very simply look like so:
$(".navbar ul li a").each(function() {
if (this.href == window.location.href) {
$(this).parent().addClass("active");
}
});
这篇关于如何在引导导航栏中添加活动类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!