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

如何在Bootstrap 4下拉菜单中实现悬停触发效果而非点击?

Hey folks, 针对之前大家提到的旧版Bootstrap方案不适用于Bootstrap 4,且没有可直接复制生效的jQuery代码的问题,我整理了一套适配Bootstrap 4的极简通用代码,直接复制到自定义脚本里就能用,覆盖了常见的交互场景~

适用于Bootstrap 4的通用jQuery解决方案

基础HTML结构(含Bootstrap 4依赖)

先确保你的页面正确引入了Bootstrap 4的CSS、jQuery和Bootstrap 4的JS,结构如下:

<head>
  <!-- Bootstrap 4 样式文件 -->
  <link rel="stylesheet" href="bootstrap4.css">
</head>
<body>
  <!-- 这里放置你的Bootstrap 4页面内容,比如模态框、导航栏、表单等 -->
  <!-- 示例触发按钮 -->
  <button id="triggerModalBtn" class="btn btn-primary">打开模态框</button>
  
  <!-- 示例模态框 -->
  <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title">示例模态框</h5>
          <button type="button" class="close" data-dismiss="modal" aria-label="Close">
            <span aria-hidden="true">&times;</span>
          </button>
        </div>
        <div class="modal-body">
          <input type="text" class="form-control" placeholder="输入内容">
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button>
        </div>
      </div>
    </div>
  </div>

  <!-- 依赖脚本引入顺序很重要:先jQuery,再Bootstrap 4 JS -->
  <script src="jquery.js"></script>
  <script src="bootstrap4.js"></script>
  <!-- 自定义脚本 -->
  <script src="custom-script.js"></script>
</body>

极简可复用jQuery代码(直接复制到custom-script.js即可)

下面的代码覆盖了Bootstrap 4中最常用的三种交互场景,你可以按需保留或修改:

$(document).ready(function() {
  // 1. 自定义模态框触发与交互
  $('#triggerModalBtn').click(function() {
    $('#exampleModal').modal('show');
  });

  // 模态框完全显示后自动聚焦输入框
  $('#exampleModal').on('shown.bs.modal', function() {
    $(this).find('.modal-body .form-control').focus();
  });

  // 2. 导航栏滚动时添加/移除阴影效果
  $(window).scroll(function() {
    const nav = $('#mainNav');
    if ($(window).scrollTop() > 50) {
      nav.addClass('shadow-sm');
    } else {
      nav.removeClass('shadow-sm');
    }
  });

  // 3. 表单输入实时验证(适配Bootstrap 4的表单状态类)
  $('.form-control').on('input blur', function() {
    const inputValue = $(this).val().trim();
    if (inputValue.length < 3) {
      $(this).removeClass('is-valid').addClass('is-invalid');
    } else {
      $(this).removeClass('is-invalid').addClass('is-valid');
    }
  });
});

代码特点

  • 完全适配Bootstrap 4的事件规范:所有交互都遵循Bootstrap 4官方的事件命名(比如shown.bs.modal)
  • 开箱即用:无需修改核心逻辑,直接复制到项目中就能运行
  • 灵活扩展:可以根据自己的需求添加更多Bootstrap 4组件的交互逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 10:01:47