常见问题

当我在 Bootstrap 模态窗口中使用 Select2 时,它无法正常工作。

此问题的发生是因为 Bootstrap 的模态窗口通常会从模态窗口之外的其他元素上窃取焦点。默认情况下,Select2将下拉菜单附加到<body>元素上时,该菜单会被认为是“在模态窗口之外”。

要避免这个问题,您可以使用dropdownParent设置将下拉菜单附加到模态窗口本身:

<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 的行为:

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

参见此回答以获得更多信息。

在使用双指缩放(pinch-zoom)时下拉菜单会出现错位/偏移。

参见#5048。问题是某些浏览器对双指缩放功能的实现会影响body元素,而Select2 默认会附加到该元素上,从而导致其渲染错误。

解决方法是使用dropdownParent将下拉菜单附加到一个更具体的元素上。

无噪 Logo
无噪文档
25 年 6 月翻译
文档源↗