JavaScript实现左侧导航栏当前活动状态高亮
作者:木棉时间:2026-10-30 10:19:28浏览:575
本文介绍利用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脚本判断当前导航状态的方法,希望能为读者提供实际帮助。若在使用过程中遇到任何疑问,欢迎留言交流,作者将及时回复。同时,感谢对本站的支持。
作者最新文章
JS中将数组和对象混合组装为JSON字符串
2026-11-05 16:41:42
JS运算符优先级与结合性的区别是什么?
2026-11-05 13:22:02
JS Map怎么只遍历Key或Value
2026-11-05 13:00:36
D3.js 与 ECharts 选型对比:灵活性 vs 开发效率
2026-11-05 09:45:01
为什么JS中typeof []返回object:数组类型检测误区解析
2026-11-04 19:50:47
