html代码:
<header> <div class="navbar-nav"> <li class="active"><a href="#">首页</a></li> <li><a href="#">新闻</a></li> <li><a href="#">活动</a></li> <li><a href="#">项目</a></li> </div> </header>
style样式代码:
header {
background-color: #3A94FF;
color: #FFF;
}
header a{
color: #FFF;
text-decoration: none;
}
li {
line-height: 50px;
background-color: #3A94FF;
display: inline-block;
padding: 0 20px;
}
li.active {
background-color: rgba(255,142,0,1.00);
}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>完整代码
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>jquery导航栏点击选中效果</title>
<script src="https://www.jq22.com/jquery/jquery-1.10.2.js"></script>
<style>
header {
background-color: #3A94FF;
color: #FFF;
}
header a{
color: #FFF;
text-decoration: none;
}
li {
line-height: 50px;
background-color: #3A94FF;
display: inline-block;
padding: 0 20px;
}
li.active {
background-color: rgba(255,142,0,1.00);
}
</style>
</head>
<body>
<header>
<div class="navbar-nav">
<li class="active"><a href="#">首页</a></li>
<li><a href="#">新闻</a></li>
<li><a href="#">活动</a></li>
<li><a href="#">项目</a></li>
</div>
</header>
<script>
$(document).ready(function (){
$(".navbar-nav>li").each(function(index){
$(this).click(function(){
$("li").removeClass("active");
$("li").eq(index).addClass("active");
});
});
});
</script>
</body>
</html>