Select2 在 select 上打开下拉菜单

Select2 open dropdown over the select

我想要这里的第一个例子https://material.angular.io/components/select/overview
我尝试了这里提供的所有方法 .
它们可以工作,但是下拉列表在打开后立即自动关闭!

发生这种情况是因为下拉菜单也获得了点击事件,因为下拉菜单正好在鼠标光标下打开!

我用这个测试过

.on('select2:open', function (e) {
      var container = $('.select2-container .select2-dropdown');
      setTimeout(function () {
        container.addClass('country-select-dropdown');
      },1000);
    })

如果我延迟重新定位,下拉菜单将不会自动关闭。

我正在考虑实现自定义下拉适配器,但对于简单的重新定位任务来说这似乎太复杂了!

有什么解决办法吗?

我也愿意使用其他库...我只需要一个自定义 select 框 ...

$(document).ready(function() {
  $('.js-example-basic-single').select2({
    dropdownAutoWidth: true,
    minimumResultsForSearch: -1,
    dropdownCssClass: 'country-select-dropdown',
    dropdownParent: $('#slectParent').parent()
  });
});
#slectParent {
  position: reletive;
}

.country-select-dropdown {
  top: -2rem;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-beta.1/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-beta.1/dist/js/select2.min.js"></script>

<div id="slectParent">
  <select class="js-example-basic-single" name="state">
    <option value="AL">Alabama</option>
    <option value="WY">Wyoming</option>
  </select>
  <div>

This happening because the dropdown is also getting the click event because the dropdown is opening exactly under the mouse cursor !

看来你是对的,我不明白为什么。可能是因为 Select2 使用 mousedown 事件打开下拉菜单,使用 click 事件打开 select 选项(鼠标事件按顺序触发 - mousedown -> mouseup -> click)

像这样的事情似乎是我在这种情况下可以提出的最佳解决方案:https://codesandbox.io/s/compassionate-kepler-fzt4h?file=/src/index.js

$(document).ready(function () {
  $(".js-example-basic-single")
    .select2({
      dropdownAutoWidth: true,
      minimumResultsForSearch: -1,
      dropdownCssClass: "country-select-dropdown",
      dropdownParent: $("#slectParent").parent()
    })
    .on("select2:open", function (e) {
      var container = $(".select2-container .select2-dropdown");
      setTimeout(function () {
        container.addClass("country-select-dropdown-open");
      }, 300);
    })
    .on("select2:closing", function (e) {
      var container = $(".select2-container .select2-dropdown");
      container.removeClass("country-select-dropdown-open");
    });
});

Css:

.country-select-dropdown {
  top: -2rem;
  pointer-events: none;
}

.country-select-dropdown-open {
  pointer-events: initial;
}

这基本上是您使用计时器的解决方案,但我没有延迟定位,而是禁用鼠标事件并在 300 毫秒后启用它们。尽管如此,这仍然不是一个完美的解决方案,并且可能会让用户感到滞后。也许你可以尝试添加一些 css 动画来重新定位,idk。

不幸的是,我不能为普通 JS 推荐任何 Select2 替代品。