Select2 在Bootstrap模态框中不能工作

出现此问题的原因是Bootstrap模态倾向于从模态外部的其他元素中窃取焦点。由于默认情况下,Select 2将下拉菜单附加到 body 元素,因此它被认为是“在模态之外”。

为了避免这个问题,你可以使用dropdownParent设置将dropdown附加到模态本身:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<div id="myModal" class="modal fade" tabindex="-1" role="dialog" aria-hidden="true">
...
<select id="mySelect2">
...
</select>
...
</div>

...

<script>
$('#mySelect2').select2({
dropdownParent: $('#myModal')
});
</script>

这将导致下拉列表被附加到模态,而不是 body元素。

或者,您可以简单地全局覆盖Bootstrap的行为:

1
2
// Do this before you initialize any of your modals
$.fn.modal.Constructor.prototype.enforceFocus = function() {};

Select2 在Bootstrap模态框中不能工作
https://itxiaopang.github.io/p/61733272a6044590ac11606f954fb48a/
作者
挨踢小胖
发布于
2023年4月18日
许可协议