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

如何点击输入框时打开Bootstrap模态框?

实现输入框/搜索图标触发Bootstrap模态框

当然可以不用按钮触发,给你两种适配Bootstrap 4的简单实现方式:

方法1:利用Bootstrap内置data属性(无需手写JS)

直接在输入框或搜索图标上添加data-toggle="modal"和data-target="#你的模态框ID"属性,点击时就能直接唤起模态框。

修改你的搜索表单代码:

<div class="input-box">
  <!-- 点击输入框触发模态框 -->
  <input type="text" class="form-control" data-toggle="modal" data-target="#searchModal">
  <!-- 或者点击搜索图标触发 -->
  <i class="fa fa-search" data-toggle="modal" data-target="#searchModal"></i>
</div>

对应的Bootstrap 4模态框示例(可替换成你自己的内容):

<!-- 模态框 -->
<div class="modal fade" id="searchModal" tabindex="-1" role="dialog" aria-labelledby="searchModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="searchModalLabel">搜索弹窗</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        这里放置你的搜索表单内容
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button>
        <button type="button" class="btn btn-primary">执行搜索</button>
      </div>
    </div>
  </div>
</div>

方法2:JavaScript手动触发(更灵活)

如果需要在打开模态框前执行额外逻辑(比如验证输入内容),可以用JS监听点击事件,手动调用模态框的show()方法:

<div class="input-box">
  <input type="text" class="form-control" id="searchInput">
  <i class="fa fa-search" id="searchIcon"></i>
</div>
// 监听输入框点击
document.getElementById('searchInput').addEventListener('click', function() {
  // 可在此添加前置逻辑,比如判断输入状态
  $('#searchModal').modal('show');
});

// 或者监听搜索图标点击
document.getElementById('searchIcon').addEventListener('click', function() {
  $('#searchModal').modal('show');
});

如果不想用jQuery,也可以用原生JS实现:

const modal = document.getElementById('searchModal');
// 显示模态框
modal.classList.add('show');
modal.style.display = 'block';
document.body.classList.add('modal-open');
// 添加模态框背景
const backdrop = document.createElement('div');
backdrop.className = 'modal-backdrop fade show';
document.body.appendChild(backdrop);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 00:22:13