You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript如何匹配任意href链接实现侧边栏激活功能

侧边栏普通路径匹配失效修复

问题根源

原有代码逻辑只针对哈希路由(带#的链接)设计:

  • 仅读取window.location.hash作为匹配依据,非哈希链接的路径信息完全没被获取
  • 哈希值为空时直接终止执行,普通路径场景下函数直接退出不运行
  • 仅监听hashchange事件,普通路径跳转、页面刷新时不会触发匹配逻辑

修改点说明

  • 替换取值逻辑:读取window.location.pathname作为当前页面路径匹配值,如果需要匹配带查询参数的路径可以拼接window.location.search
  • 删除哈希为空直接返回的判断
  • 新增popstate事件监听,适配history模式路由的路径切换场景
  • 保留原有侧边栏展开、激活态切换的逻辑不变,兼容原有哈希路由场景

修改后完整代码

<script>
  (() => {
    'use strict'

    function setActiveItem() {
      // 取当前页面路径,需要匹配带查询参数的场景可改为 const currentPath = window.location.pathname + window.location.search
      const currentPath = window.location.pathname
      
      // 匹配href和当前路径一致的侧边栏链接
      const link = document.querySelector(`.d-flex a[href="${currentPath}"]`)

      if (!link) {
        return
      }

      const active = document.querySelector('.d-flex .active')
      const parent = link.parentNode.parentNode.previousElementSibling

      link.classList.add('active')

      if (parent.classList.contains('collapsed')) {
        parent.click()
      }

      if (!active) {
        return
      }

      const expanded = active.parentNode.parentNode.previousElementSibling

      active.classList.remove('active')

      if (expanded && parent !== expanded) {
        expanded.click()
      }
    }

    setActiveItem()
    // 监听history路由变化,多页场景下保留这行也不会有负面影响
    window.addEventListener('popstate', setActiveItem)
    // 兼容原有哈希路由场景
    window.addEventListener('hashchange', setActiveItem)
  })()
</script>

注意:如果项目里a标签的href写的是带域名的完整地址,可以在匹配时对比link.pathname和当前页面pathname,避免域名、协议差异导致匹配失败。

内容的提问来源于stack exchange,提问作者mario7111

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.28 06:12:22