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

如何用JavaScript在多页面中保持下拉菜单展开/激活状态?

实现页面加载时自动匹配并展开对应下拉菜单

需求:当访问特定页面(例如www.website.com/bienetre.html)时,自动匹配菜单中的对应链接,展开其所属的下拉菜单,并给该链接添加激活样式,无需用户手动逐个展开下拉菜单。

原代码存在的问题

  1. URL匹配逻辑错误:直接用完整的location.href和链接的相对href属性对比,二者格式不一致,无法匹配成功
  2. jQuery依赖错误:代码中使用$(this)但未引入jQuery库,且循环内的this指向错误,无法获取到目标元素
  3. 核心逻辑缺失:未实现展开下拉菜单和给当前链接添加激活类的关键代码

修正后的完整实现代码

HTML结构(保留原结构,统一链接格式)

<head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <style>
    /* 下拉菜单默认隐藏 */
    .dropdown-container {
      display: none;
    }
    /* 下拉按钮激活状态样式 */
    .dropdown-btn.active {
      background-color: #ddd;
      font-weight: bold;
    }
    /* 当前链接激活样式 */
    .active-link {
      color: #ff0000;
      font-weight: bold;
    }
  </style>
</head>

<body>
  <div id="subNavLeft" class="mainNav2017sub desktop">
    <div class="subNavCol">
      <div id="headerSub1">ORIENTATION</div>

      <button type="button" class="dropdown-btn"> Bien être et counseling</button>

      <div class="dropdown-container">
        <ul>
          <li>
            <p><a href="bienetre.html">Bienêtre et santé mentale</a></p>
          </li>
          <li>
            <p><a href="vie-spirituelle.html">Vie spirituelle</a></p>
          </li>
        </ul>
      </div>

      <button type="button" class="dropdown-btn"> Orientation</button>

      <div class="dropdown-container">
        <ul>
          <li>
            <p><a href="respect-en-milieu-detude.html">Respect en milieu d'étude</a></p>
          </li>
          <li>
            <p><a href="orientation.html">Service d'orientation pédagogique</a></p>
          </li>
          <li>
            <p><a href="droits-et-recours.html">Droits et recours des étudiants</a></p>
          </li>
          <li>
            <p><a href="prets.html">Prêts aux étudiants</a></p>
          </li>
          <li>
            <p><a href="emploietudiant.html">Emplois pour étudiants</a></p>
          </li>
        </ul>
      </div>

      <div class="dropdown-container">
        <ul>
          <li>
            <p><a href="annuaire.html">Détails sur l'admission, les exigences et les règlements</a></p>
          </li>
        </ul>
      </div>
    </div>
  </div>

  <script>
    // 下拉按钮点击切换逻辑
    const dropdownBtns = document.querySelectorAll(".dropdown-btn");
    dropdownBtns.forEach(btn => {
      btn.addEventListener("click", function() {
        this.classList.toggle("active");
        const dropdownContent = this.nextElementSibling;
        dropdownContent.style.display = dropdownContent.style.display === "block" ? "none" : "block";
      });
    });

    // 页面加载时自动匹配并展开对应菜单
    document.addEventListener("DOMContentLoaded", function() {
      const currentPath = location.pathname;
      const links = document.querySelectorAll(".dropdown-container a");

      links.forEach(link => {
        // 将相对链接转为绝对路径的部分,确保匹配准确
        const linkPath = new URL(link.href, location.origin).pathname;
        if (linkPath === currentPath) {
          // 给当前链接添加激活类
          link.classList.add("active-link");
          // 找到所属的下拉容器
          const dropdownContainer = link.closest(".dropdown-container");
          if (dropdownContainer) {
            // 展开下拉容器
            dropdownContainer.style.display = "block";
            // 找到对应的下拉按钮并添加激活类
            const dropdownBtn = dropdownContainer.previousElementSibling;
            if (dropdownBtn && dropdownBtn.classList.contains("dropdown-btn")) {
              dropdownBtn.classList.add("active");
            }
          }
        }
      });
    });
  </script>
</body>

关键代码解释

  1. URL匹配优化:使用location.pathname获取当前页面的路径部分,通过new URL(link.href, location.origin).pathname将链接的相对路径转为统一的绝对路径格式,确保匹配准确
  2. DOM遍历逻辑:找到匹配的链接后,用closest('.dropdown-container')向上查找所属的下拉容器,再通过previousElementSibling找到对应的下拉按钮
  3. 状态设置:给匹配的链接添加active-link样式类,展开下拉容器并给下拉按钮添加active类,保持和手动点击一致的视觉状态
  4. 事件监听时机:用DOMContentLoaded确保DOM加载完成后再执行匹配逻辑,避免找不到元素的问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 03:15:43