html代码:
<header>
<div class="navbar-nav">
<li class="active"><a href="index.html">首页</a></li>
<li><a href="news.html">新闻</a></li>
<li><a href="activity.html">活动</a></li>
<li><a href="project.html">项目</a></li>
</div>
</header>
style样式代码:
<style>
header{
background-color: #C50B10;
color: #FFF;
}
li{
line-height: 50px;
background-color: #C50B10;
display: inline-block;
padding: 0 20px;
}
li.active{
background: rgba(0,0,0,.2);
}
</style>
js代码:
<script>
$(document).ready(function (){
$(".navbar-nav>li").each(function(index){
$(this).click(function(){
$("li").removeClass("active");
$("li").eq(index).addClass("active");
});
});
});
</script>
实现效果:
但是一般页面的导航栏都是需要跳转页面的,上面的方法只在当前页面有效,跳转后就失效了。
要实现跳转后,对应的栏目自动添加选中效果,可以用下面的方法。
js代码:
<script>
$(document).ready(function () {
$(".navbar-nav>li a").each(function () {
if ($($(this))[0].href == String(window.location))
$(this).parent().addClass('active');
});
});
</script>