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

Bootstrap 5:点击下拉按钮内元素时禁止菜单展开/收起

Bootstrap 5 下拉按钮内图标点击不触发菜单切换的解决办法

问题:下拉按钮内部的.inside-button图标绑定了点击事件,点击该图标时,下拉菜单会同时展开/收起,需要实现仅执行图标点击动作、不触发下拉菜单状态切换的效果。

解决方法:在图标的点击事件处理函数中添加e.stopPropagation(),阻止事件向上冒泡到父级按钮,从而避免触发Bootstrap的下拉切换逻辑。

修改后的代码如下:

<html>
<head>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">
<script src="https://code.jquery.com/jquery-3.7.1.slim.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>

</head>
<body>
<div class="dropdown">
  <button class="btn btn-primary dropdown-toggle" type="button" data-bs-toggle="dropdown" aria-expanded="false">
    Dropdown button <i class="bi bi-x inside-button"></i>
  </button>
  <ul class="dropdown-menu">
    <li><a class="dropdown-item" href="#">Action</a></li>
    <li><a class="dropdown-item" href="#">Another action</a></li>
    <li><a class="dropdown-item" href="#">Something else here</a></li>
  </ul>
</div>
<script>
$('.inside-button').on('click', function(e) {
    e.stopPropagation(); // 阻止事件冒泡
    console.log(new Date());
});
</script>
</body>
</html>

原理说明

Bootstrap 5的下拉组件通过监听按钮的click事件来切换菜单的显示状态。由于图标是按钮的子元素,点击图标时,click事件会向上冒泡到父级按钮,触发下拉切换逻辑。使用e.stopPropagation()可以终止事件的冒泡过程,确保只有图标的点击事件被执行,不会触发按钮的下拉行为。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 20:03:15