index.html代码内容
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>导航高亮显示</title>
<style type="text/css">
body{
font-size:20px;
}
.nav{
list-style-type: none;
margin:0;
padding:0;
}
.clear:after{
content:'/20';
display:block;
clear:both;
height:0;
visibility: hidden;
}
.nav li{
float:left;
background:#B1DFF5;
margin-right:1px;
color:#fff;
}
.nav li a{
display:block;
height:45px;
width:120px;
line-height:45px;
text-align:center;
text-decoration:none;
}
.active{
background:#28b1f3;
font-weight:bold;
}
</style>
</head>
<body>
<ul class="nav clear" id="nav">
<li><a href="index.html">首页</a></li>
<li><a href="1.html">栏目一</a></li>
<li><a href="2.html">栏目二</a></li>
<li><a href="3.html">栏目三</a></li>
</ul>
</body>
<script type="text/javascript" src="js/jquery-1.7.min.js"></script>
<script type="text/javascript">
var urlstr = location.href;
console.log(urlstr+'/');
var urlstatus=false;
$("#nav a").each(function () {
if ((urlstr + '/').indexOf($(this).attr('href')) > -1&&$(this).attr('href')!='') {
$(this).addClass('active'); urlstatus = true;
} else {
$(this).removeClass('active');
}
});
if (!urlstatus) {$("#nav a").eq(0).addClass('active'); }
</script>
</html>
1.html代码内容
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>栏目一</title>
<style type="text/css">
body{
font-size:20px;
}
.nav{
list-style-type: none;
margin:0;
padding:0;
}
.clear:after{
content:'/20';
display:block;
clear:both;
height:0;
visibility: hidden;
}
.nav li{
float:left;
background:#B1DFF5;
margin-right:1px;
color:#fff;
}
.nav li a{
display:block;
height:45px;
width:120px;
line-height:45px;
text-align:center;
text-decoration:none;
}
.active{
background:#28b1f3;
font-weight:bold;
}
</style>
</head>
<body>
<ul class="nav clear" id="nav">
<li><a href="index.html">首页</a></li>
<li><a href="1.html">栏目一</a></li>
<li><a href="2.html">栏目二</a></li>
<li><a href="3.html">栏目三</a></li>
</ul>
<h1>栏目一</h1>
</body>
<script type="text/javascript" src="js/jquery-1.7.min.js"></script>
<script type="text/javascript">
var urlstr = location.href;
console.log(urlstr+'/');
var urlstatus=false;
$("#nav a").each(function () {
if ((urlstr + '/').indexOf($(this).attr('href')) > -1&&$(this).attr('href')!='') {
$(this).addClass('active'); urlstatus = true;
} else {
$(this).removeClass('active');
}
});
if (!urlstatus) {$("#nav a").eq(0).addClass('active'); }
</script>
</html>
效果图
注意:
1 location.href 用于获取当前页面的url
2 当前页面应该保存为index.html
3 indexOf 用于检索当前url中是否存在a中对应的href
4 每个html中都拥有相同的导航结构
5 eq(index/-index) 获取当前链式操作中第N个JQuery对象,返回JQquery对象,当参数大于等于0时为正向选取,比如0代表第一个,1代表第二个。当参数为负数时为反向选取,比如-1代表倒数第一个。