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

如何在Bootstrap 5中点击下拉按钮时激活首个菜单项

Bootstrap 5下拉菜单打开时自动高亮首个菜单项

当前Bootstrap 5下拉菜单点击触发按钮后,首个菜单项不会自动获得焦点(高亮),需按下方向键才能激活高亮状态。要实现类似Windows桌面应用菜单的效果,可通过监听Bootstrap的下拉事件来自动为首个菜单项设置焦点。

解决方案代码

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.0/dist/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.0/dist/js/bootstrap.bundle.min.js"></script>

<div class="btn-group">
  <button type="button" class="btn btn-danger dropdown-toggle" data-bs-toggle="dropdown" aria-expanded="false">
    Action
  </button>
  <ul class="dropdown-menu">
    <li><a class="dropdown-item" href="#"><u>A</u>ction</a></li>
    <li><a class="dropdown-item" href="#">A<u>n</u>other action</a></li>
    <li><a class="dropdown-item" href="#"><u>S</u>omething else here</a></li>
    <li><hr class="dropdown-divider"></li>
    <li><a class="dropdown-item" href="#">S<u>e</u>parated link</a></li>
  </ul>
</div>

<script>
// 监听下拉菜单显示完成事件
document.addEventListener('shown.bs.dropdown', function (e) {
  // 获取当前下拉菜单中的首个可交互菜单项
  const firstItem = e.target.querySelector('.dropdown-item:first-of-type');
  if (firstItem) {
    // 为首个菜单项设置焦点,触发Bootstrap的高亮样式
    firstItem.focus();
    // 可选:添加active类保持高亮(若需要点击后仍保留状态)
    // firstItem.classList.add('active');
  }
});
</script>

代码说明

  • 事件监听:使用shown.bs.dropdown事件,确保在下拉菜单完全渲染显示后再执行操作,避免元素未加载完成的问题。
  • 定位首个菜单项:通过querySelector('.dropdown-item:first-of-type')精准获取第一个可交互的下拉菜单项,自动跳过分隔线元素。
  • 设置焦点:调用focus()方法让菜单项获得焦点,Bootstrap默认的:focus样式会自动高亮该元素,实现类似Windows菜单的效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 18:50:11