JavaScript实现左侧导航栏当前活动状态高亮

作者:木棉

时间:2026-10-30

浏览:574

本文介绍利用JavaScript和jQuery判断当前页面链接并高亮显示左侧导航栏的方法。通过获取URL文件名并与导航链接比对,为匹配项添加active类,同时处理子菜单的展开与折叠,确保导航状态与当前页面一致。

文章目录

JavaScript实现左侧导航栏当前活动状态高亮

直接展示核心实现代码。

核心代码实现


<script>
$(function () {
//highlight current / active link 左侧导航判断当前活动导航
$('ul.main-menu li a').each(function () {
var wo = window.location.href.substring(window.location.href.lastIndexOf('/') + 1, window.location.href.lastIndexOf('.'));
if ($(this).attr('href') == (wo + ".html")) {
$(this).parent().addClass('active');
$(this).parents().addClass('active');
$(this).parents('li').find("i:first").toggleClass("glyphicon-minus");
$(this).parents('ul').slideDown();
}else
if (("dxs" == wo || "syd" == wo)&&($(this).attr('href')=="dbs.html")) {
$(this).parent().addClass('active');
$(this).parents().addClass('active');
$(this).parents('li').find("i:first").toggleClass("glyphicon-minus");
$(this).parents('ul').slideDown();
}
});
/*** begin 主页左侧菜单 */ 
$(".main-menu a").click(function () {
//将当前li设置为活动状态
$(this).find("i:first").toggleClass("glyphicon-minus");
});
$(".main-menu a").click(function () {
//更换其他导航的加减号图标
$(this).parent('li').siblings(".active").find("i:first").toggleClass("glyphicon-minus");
//alert($(this).index());
//去掉其他导航的点击样式并折叠
$(this).parent('li').siblings(".active").removeClass("active").children("ul").slideUp('fast');
$(this).next('ul').slideToggle('fast');
$(this).parent('li').addClass('active');
});
/************** end 主页左侧菜单 */
})
</script>

上述内容介绍了利用JavaScript脚本判断当前导航状态的方法,希望能为读者提供实际帮助。若在使用过程中遇到任何疑问,欢迎留言交流,作者将及时回复。同时,感谢对本站的支持。

实用工具推荐

电子包浆

绿化、压缩、噪点和虚拟水印,自由调节做旧程度。

使用 ›
图片压缩

选择画质和输出格式,预览压缩前后的大小。

使用 ›
相关文章