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

Bootstrap 5导航栏下拉菜单异常求助:移动端点击不关闭、桌面端变白

问题1:移动端点击下拉菜单无法收起

你的自定义JS存在两处关键问题:

  1. HTML中Services下拉按钮未设置id="servicesDropdown",导致JS无法获取目标元素
  2. 绑定的click事件直接阻止默认行为,覆盖了Bootstrap原生的下拉切换逻辑,导致点击无法触发收起

修正方案:

  • 先给下拉按钮补上ID:
<a class="nav-link dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown" aria-expanded="false" id="servicesDropdown">
  Services
</a>
  • 重写JS逻辑,仅在桌面端启用hover展开,移动端保留Bootstrap原生点击交互:
const servicesDropdown = document.getElementById('servicesDropdown');
const dropdownMenu = servicesDropdown.nextElementSibling;

// 桌面端hover展开逻辑
function initDesktopDropdown() {
  const dropdownContainer = servicesDropdown.closest('.dropdown');
  
  servicesDropdown.addEventListener('mouseenter', () => {
    servicesDropdown.setAttribute('aria-expanded', 'true');
    dropdownMenu.classList.add('show');
  });

  // 监听鼠标离开整个下拉容器(按钮+菜单)
  dropdownContainer.addEventListener('mouseleave', () => {
    servicesDropdown.setAttribute('aria-expanded', 'false');
    dropdownMenu.classList.remove('show');
  });
}

// 仅在桌面端(Bootstrap lg断点)启用hover逻辑
if (window.matchMedia('(min-width: 992px)').matches) {
  initDesktopDropdown();
}

// 窗口大小变化时重新适配
window.addEventListener('resize', () => {
  dropdownMenu.classList.remove('show');
  servicesDropdown.setAttribute('aria-expanded', 'false');
  
  if (window.matchMedia('(min-width: 992px)').matches) {
    initDesktopDropdown();
  }
});

问题2:桌面端点击下拉菜单后移开光标变白

点击下拉按钮后,Bootstrap会给.dropdown-menu添加show类,但你的CSS仅在hover状态下设置背景色,hover消失后show类仍存在却无对应样式,导致菜单背景变白。

修正方案:
修改CSS,给show类也添加背景色设置:

/* 合并hover和show状态的背景样式 */
.dropdown:hover .dropdown-menu,
.dropdown-menu.show {
  display: block;
  background-color: hsl(210, 45%, 30%);
}

/* 保留原有菜单尺寸等样式 */
.dropdown:hover>.dropdown-menu {
  margin-top: 0;
  width: 175px;
}

额外优化提示

  • 清理CSS中多余的闭合括号(代码末尾存在未匹配的}),避免样式错乱
  • 使用Bootstrap官方断点(如992px对应桌面端)代替自定义断点,更贴合框架设计逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 05:32:02