嵌入Bootstrap模态框的Slim Select搜索框无法输入的解决方法
问题描述
当在Bootstrap模态框中使用Slim Select组件时,无法在其搜索框中输入内容。在模态框外,Slim Select组件功能正常。

我的代码
HTML
<div class="modal modal-blur fade" id="modal-report" role="dialog" aria-hidden="true"> <div class="modal-dialog modal-lg modal-dialog-centered" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title">New report</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> <div class="row"> <div class="col-lg-6"> <div class="mb-3"> <label class="form-label">Client name</label> <select id="selectElement"> <option value="value1">Value 1</option> <option value="value2">Value 2</option> <option value="value3">Value 3</option> </select> </div> </div> <div class="col-lg-6"> <div class="mb-3"> <label class="form-label">Reporting period</label> <input type="date" class="form-control"> </div> </div> <div class="col-lg-12"> <div> <label class="form-label">Additional information</label> <textarea class="form-control" rows="3"></textarea> </div> </div> </div> </div> <div class="modal-footer"> <a href="#" class="btn btn-link link-secondary" data-bs-dismiss="modal"> Cancel </a> <a href="#" class="btn btn-primary ms-auto" data-bs-dismiss="modal"> <!-- Download SVG icon from http://tabler-icons.io/i/plus --> <svg xmlns="http://www.w3.org/2000/svg" class="icon" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M12 5l0 14" /><path d="M5 12l14 0" /></svg> Create new report </a> </div> </div> </div> </div>
JS
<script> document.addEventListener('DOMContentLoaded', function () { new SlimSelect({ select: '#selectElement' }); }); </script>
模态框内的搜索框无法使用也无法点击,但在模态框外功能正常。该如何解决这个问题?
解决方法
这个问题源于Bootstrap模态框的焦点拦截机制:Bootstrap会强制将焦点锁定在模态框内部,而Slim Select的搜索框是动态生成在模态框DOM结构之外的,因此无法获取输入焦点。
下面提供两种可靠的解决方式:
方法一:禁用Bootstrap模态框的自动焦点管理
直接关闭Bootstrap模态框的焦点强制锁定功能,这样外部生成的搜索框就能正常获取焦点了。
如果是通过JS初始化模态框,添加focus: false选项:
const modal = new bootstrap.Modal(document.getElementById('modal-report'), { focus: false });
如果是通过HTML属性触发模态框,给模态框元素添加data-bs-focus="false":
<div class="modal modal-blur fade" id="modal-report" data-bs-focus="false" role="dialog" aria-hidden="true">
方法二:将Slim Select的下拉框嵌入模态框内部
初始化Slim Select时,指定appendTo参数为模态框的内容容器,让搜索框生成在模态框DOM结构之内,从而绕过焦点拦截:
document.addEventListener('DOMContentLoaded', function () { new SlimSelect({ select: '#selectElement', appendTo: document.querySelector('#modal-report .modal-content') }); });
两种方法都可以解决问题,优先推荐第一种,无需改动组件DOM结构,更符合Bootstrap的设计逻辑。
内容的提问来源于stack exchange,提问作者Md. Shamvil Hossain
相关产品推荐
相关产品推荐

