应使用 window.location.pathname 精准匹配路径,避免 href 全量比较;需解析链接为 new URL(this.href, origin).pathname,/ 要匹配 /、/index.html 等;禁用 indexOf 前缀匹配;必须同时添加 class="active" 和 aria-current="page";SPA 需监听路由变化重执行逻辑。

用 window.location.pathname 精准匹配路径,别比完整 URL
直接用 window.location.href === this.href 会失败,因为协议、端口、查询参数(如 ?ref=nav)、尾部斜杠(/ vs /index.html)都会导致不等。真正稳定的依据是路径部分 —— window.location.pathname。
关键点:
- 用
new URL(this.href, window.location.origin).pathname解析每个链接的路径,避免相对路径误判 - 首页要单独处理:
/应匹配/、/index.html、/index.htm - 不要用
indexOf()做前缀匹配,否则/blog会错误激活/blog-post
必须同时加 class="active" 和 aria-current="page"
只加 class="active" 是视觉高亮,对屏幕阅读器无效;只加 aria-current="page" 而没配 CSS,则用户看不见变化。两者缺一不可。
正确写法示例:
<a href="/dashboard" class="nav-link" aria-current="page">Dashboard</a>
CSS 推荐用属性选择器,更语义化:
a[aria-current="page"] { font-weight: bold; background-color: #007bff; color: white; }
注意:
- 别写
aria-current="true"—— 它缺乏语义,读屏器只读“当前”,不说明是“当前页面” - 如果导航项是
或非链接元素,必须加role="link"和tabindex="0"才能被键盘和读屏器识别
服务端渲染(如 Flask + Jinja2)优先用 request.endpoint
比前端 JS 更可靠:首屏即高亮、无 FOUC、SEO 友好、不依赖 JS 执行。
典型结构:
<nav class="sidebar"><a href="%7B%7B%20url_for('dashboard')%20%7D%7D" class="sidebar-link {% if request.endpoint == 'dashboard' %}active{% endif %}" aria-current="{% if request.endpoint == 'dashboard' %}page{% else %}false{% endif %}">
Dashboard
</a>
<a href="%7B%7B%20url_for('feature1')%20%7D%7D" class="sidebar-link {% if request.endpoint == 'feature1' %}active{% endif %}" aria-current="{% if request.endpoint == 'feature1' %}page{% else %}false{% endif %}">
Feature 1
</a>
</nav>
要点:
-
request.endpoint是视图函数名,不是 URL 路径,不受路由参数或重定向干扰 - Flask 的
url_for()生成绝对安全的 href,避免硬编码路径出错 - 不要在模板里拼接字符串判断
request.url—— 容易因查询参数或子路径失效
单页应用(SPA)需监听路由变化
纯 HTML 页面刷新后自动重跑脚本,但 SPA(React/Vue)切换路由时 DOM 不重载,JS 不会自动重执行。
必须监听:
- React Router:在组件内用
useEffect+useLocation;或用NavLink组件(它内置了aria-current支持) - Vue Router:用
watch监听$route,或直接使用(自动加router-link-exact-active类和aria-current) - 原生 History API:监听
popstate事件,并重新运行高亮逻辑
漏掉这步,导航菜单会“卡”在旧状态,用户点进新页面后高亮项不变 —— 这是最常被忽略的复杂点。
前端入门到VUE实战笔记:立即使用
在学习笔记中,你将探索 前端 的入门与实战技巧!











