Bootstrap Modal无法使用Select2下拉菜单滚动

aij0ehis  于 2023-02-06  发布在  Bootstrap
关注(0)|答案(1)|浏览(230)

我有一个bootstrap模态与select2下拉内:

<div id="add-event" class="modal" role="dialog">
    <div class="modal-dialog">
        <div class="modal-content">

            ....

            <div class="organizer-options form-group id="organizer-search">
                <span>Hosted by:</span>
                <select class="form-control organizer-search" name="organizer-search" autocomplete="off">
                </select>
            </div>

我在一个单独的JS文件中初始化select2:

$(".organizer-search").select2({
    dropdownParent: $("#add-event"),
    minimumInputLength: 3,
    placeholder: "Select the host",
    ajax: {
        url: "/people/search",
        method: "get",
        dataType: "json",
        delay: 250,
        data: function(params) {
            return {
                term: params.term
            };
        },
        processResults: function(data) {
            return {
                results: data
            };
        }
    }
});

我将dropdownParent: $("#add-event")行添加到select2 init中,因为否则我无法关注模态中的select2。我还在初始化所有模态之前尝试了$.fn.modal.Constructor.prototype.enforceFocus = function() {};
这两个选项都支持聚焦于下拉菜单,但在移动的(chrome和firefox)上禁用滚动模式。

cetgtptt

cetgtptt1#

首先在select2选项中必须有

dropdownParent: $(this).parent(),// That fix weird positioning select2 input

之后我们在select2打开事件时做了一些小技巧。我意识到如果模态高度小于窗口高度,当select2打开时滚动没有问题,即使在需要滚动之后。
所以我们对select2事件进行了溢出调整。当打开select2时,将模态体设置为无溢出,在select2打开后,将其设置回默认值。

$(document).on("select2:opening", (e) => {
        $('.modal-body').css('overflow', 'visible');
    });
    $(document).on("select2:open", (e) => {
        $('.modal-body').css('overflow', 'auto');
    });

这会解决你的问题。

相关问题