導航菜單點擊切換時保持高亮狀態(JS實現)示例
嘗試每個頁面的導航欄目後加class=“active”屬性進行修改不成功,這時就需要靈活使用javascript來搞定。
實現效果如圖 :
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>導航菜單切換高亮選擇項1</title>
</head>
<body>
<style>
.redtd{
background-color:#FFC926; font-weight:bold;
}
</style>
<script type="text/javascript" src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
<script type="text/javascript" >
$(function(){
$('td').click(function(){
$(this).toggleClass('redtd').siblings().removeClass('redtd');
});
});
//默認點亮第一個
$('#tsel1 td:eq(1)').toggleClass('redtd');
</script>
<div>
<table id="tsel1" style="margin-top: 8px;">
<tr height="35">
<td style="width:119px;"><a >參數信息導航</a></td>
<td style="width:120px;"
bgcolor="#E5E5E5" onMouseOut="javascript:this.bgColor='#E5E5E5';"
onMouseMove="javascript:this.bgColor='#FFC926';" >
<a href="#">參數導航一</a>
</td>
<td style="width:120px;"
bgcolor="#E5E5E5" onMouseOut="javascript:this.bgColor='#E5E5E5';"
onMouseMove="javascript:this.bgColor='#FFC926';" >
<a href="#">參數導航二</a>
</td>
<td style="width:5px;"></td>
<td style="width:120px;" class="center"
bgcolor="#E5E5E5" onMouseOut="javascript:this.bgColor='#E5E5E5';"
onMouseMove="javascript:this.bgColor='#FFC926';" >
<a href="#">參數導航三</a>
</td>
<td style="width:5px;"></td>
<td style="width:120px;" class="center"
bgcolor="#E5E5E5" onMouseOut="javascript:this.bgColor='#E5E5E5';"
onMouseMove="javascript:this.bgColor='#FFC926';" >
<a href="#">參數導航四</a>
</td>
<td style="width:5px;"></td>
</tr>
</table>
</div>
</body>
</html>
另外一種實現方式,效果如圖:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>導航菜單切換高亮選擇項</title>
</head>
<body>
<style>
.menu { padding:0; margin:0; list-style-type:none;}
.menu li { background:#FFD1A4; margin-right:1px; float:left; color:#fff; }
.menu li a { display:block; width:80px; text-align:center; height:32px; line-height:32px; color:#fff; font-size:13px; text-decoration:none;}
.cursel{ background:#D96C00; font-weight:bold;}
</style>
<ul class="menu" id="menu">
<li><a href="demo1.html?id=0">首頁</a></li>
<li><a href="demo1.html?id=1">導航一</a></li>
<li><a href="demo1.html?id=2">導航二</a></li>
<li><a href="demo1.html?id=3">導航三</a></li>
<li><a href="demo1.html?id=4">導航四</a></li>
</ul>
<script type="text/javascript" src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
<script type="text/javascript">
var urlstr = location.href;
var urlstatus=false;
$("#menu a").each(function () {
if ((urlstr + '/').indexOf($(this).attr('href')) > -1&&$(this).attr('href')!='') {
$(this).addClass('cursel'); urlstatus = true;
} else {
$(this).removeClass('cursel');
}
});
if (!urlstatus) {$("#menu a").eq(0).addClass('cursel'); }
</script>
</body>
</html>
代碼可以直接拷貝測試,原理盡在代碼中,主要用到添加類樣式addClass(),刪除類樣式removeClass(),切換類樣式toggleClass()等。