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

如何在dropdown菜单项对应的页面中,保持该下拉菜单背景为灰色?

实现下拉菜单按钮的当前板块高亮效果

针对你的疑问直接解答:

  • 不需要设置两个dropdown类:复用现有.dropdown和.dropbtnhref类,只需要新增一个通用的激活状态类(比如active)即可,不用重复定义样式。
  • 不推荐用内联样式:内联样式需要在每个页面手动修改,维护麻烦,而且无法动态切换状态,完全没必要用。
  • 直接给按钮加激活状态样式是最简便的方案:不用改动现有HTML结构的核心逻辑,只需要给对应按钮添加激活类,配合CSS就能实现高亮。

具体实现步骤:

1. 优化HTML结构(给按钮加板块标识)

给每个下拉菜单的按钮添加一个data-section属性,用来标记这个按钮所属的板块,方便后续判断:

<!-- APPLICATION PAGE 下拉菜单 -->
<div class="dropdown">
  <button class="dropbtnhref" data-section="application">APPLICATION PAGE
    <i class="fa fa-caret-down"></i>
  </button>
  <div class="dropdown-content">
    <a href="../page">PAGE 1</a>
    <a href="../page2.htm">PAGE 2</a>
    <a href="../page3.htm">PAGE 3</a>
    <a href="../page4.htm">PAGE 4</a>
    <a href="../page5.htm">PAGE 5</a>
    <a href="../page6.htm">PAGE 6</a> 
    <a href="../page7.htm">PAGE 7</a> 
  </div>
</div>

<!-- TECHNICAL PAGE 下拉菜单 -->
<div class="dropdown">
  <button class="dropbtnhref" data-section="technical">TECHNICAL PAGE
    <i class="fa fa-caret-down"></i>
  </button>
  <div class="dropdown-content">
    <a href="../page22.htm">PAGE 22</a>
    <a href="../page23.htm">PAGE 23</a>
    <a href="../page25.htm">PAGE 25</a>
    <a href="../page26.htm">PAGE 26</a>
    <a href="../page27.htm">PAGE 27</a>
  </div>
</div>

2. 添加CSS激活状态样式

在现有CSS基础上,新增激活状态的样式,给按钮设置灰色背景:

/* 保留你原有的按钮样式 */
.dropbtnhref {
  /* 你的原有样式,比如 padding、字体、边框等 */
  background-color: #你的默认背景色;
}

/* 激活状态样式 - 当前板块的按钮会显示灰色背景 */
.dropbtnhref.active {
  background-color: #ccc; /* 可根据需求调整灰色深浅 */
  color: #333; /* 可选:调整文字颜色增强辨识度 */
}

3. 用JS自动判断并添加激活类

在页面加载时,通过当前页面的路径判断属于哪个板块,给对应按钮加上active类:

// 获取当前页面的路径
const currentPage = window.location.pathname;

// 判断当前页面属于APPLICATION板块
const applicationPages = ['page', 'page2.htm', 'page3.htm', 'page4.htm', 'page5.htm', 'page6.htm', 'page7.htm'];
if (applicationPages.some(page => currentPage.includes(page))) {
  document.querySelector('[data-section="application"]').classList.add('active');
}

// 判断当前页面属于TECHNICAL板块
const technicalPages = ['page22.htm', 'page23.htm', 'page25.htm', 'page26.htm', 'page27.htm'];
if (technicalPages.some(page => currentPage.includes(page))) {
  document.querySelector('[data-section="technical"]').classList.add('active');
}

(可选)服务器端渲染方案更稳定

如果你的页面是服务器端生成的(比如PHP、Node.js),可以直接在对应页面的按钮上手动添加active类,不用JS判断,比如在PAGE1的页面中,APPLICATION的按钮写成:

<button class="dropbtnhref active" data-section="application">APPLICATION PAGE
  <i class="fa fa-caret-down"></i>
</button>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 09:30:24