如何实现菜单栏当前所在页面选项的高亮显示
导航栏高亮不生效问题排查与解决方案
问题根因
不生效问题由以下几个错误共同导致:
- 路径判断存在多余空格:条件语句
{% if request.path == " / " %}中,路径/前后带了多余空格,实际请求路径是不带空格的/,条件永远无法匹配。 - HTML标签语法错误:所有
<li>标签写完属性后都缺少闭合的>符号,导致class属性无法被浏览器正确识别;另外首页<a>标签的aria-label属性缺少左侧引号,也会干扰标签属性解析。 - 仅给首页加了判断逻辑:「关于我们」「Services」相关菜单没有加对应路径的匹配判断,切换到对应页面时自然不会触发高亮。
修复方案
方案1:服务端模板修复(推荐)
先修正所有语法错误,再给每个菜单项加上对应路径判断即可,修正后的代码如下:
{% if user %} <!--Option 1 首页--> <li role="none" class="weblink mr-3 {% if request.path == '/' %}active{% endif %}"> <a role="menuitem" aria-label="Home page" href="/" title="Home page"> Home page </a> </li> <!--Option 2 服务下拉菜单--> <li role="none" class="weblink dropdown {% if request.path starts with '/services/' %}active{% endif %}"> <a role="menuitem" aria-label="Services" href="#" class="dropdown-toggle" data-toggle="dropdown" title="Services"> Services <span class="caret"></span> </a> <ul class="dropdown-menu" role="menu"> <li role="none" class="{% if request.path == '/services/' %}active{% endif %}"> <a role="menuitem" aria-label="Services" href="/services/" title="Services">Services</a> </li> <div class="divider"></div> <li role="none" class="{% if request.path == '/services/product-a/' %}active{% endif %}"> <a role="menuitem" aria-label="Product A (example)" href="/services/product-a/" title="Product A (example)"> Product A (example) </a> </li> <li role="none" class="{% if request.path == '/services/product-b/' %}active{% endif %}"> <a role="menuitem" aria-label="Product B (example)" href="/services/product-b/" title="Product B (example)"> Product B (example) </a> </li> </ul> </li> <!--Option 3 关于我们--> <li role="none" class="weblink {% if request.path == '/about-us/' %}active{% endif %}"> <a role="menuitem" aria-label="About us" href="/about-us/" title="About us"> About us </a> </li> {% endif %} <!--End Options-->
优化说明:公共类名统一写到外面,判断逻辑仅控制是否追加active类,代码更简洁易维护
方案2:前端jQuery实现
无需修改服务端模板的情况下,可以用以下代码实现高亮逻辑,页面加载时自动匹配当前路径高亮,点击时也会自动切换状态:
$(function(){ // 页面加载时自动高亮当前路径对应菜单 const currentPath = window.location.pathname; $('.weblink a').each(function(){ if($(this).attr('href') === currentPath){ $(this).parent('.weblink').addClass('active').siblings('.weblink').removeClass('active'); // 下拉菜单子项被选中时同时高亮父级菜单 if($(this).parents('.dropdown').length){ $(this).parents('.dropdown').addClass('active'); } } }) // 点击菜单时切换高亮状态 $('.weblink a').click(function(){ $(this).parent('.weblink').addClass('active').siblings('.weblink').removeClass('active'); if($(this).parents('.dropdown').length){ $(this).parents('.dropdown').addClass('active'); } }) })
内容的提问来源于stack exchange,提问作者Martin Vargas
相关产品推荐
相关产品推荐

