美文网首页
select2在bootstrap模态框无法获取焦点问题

select2在bootstrap模态框无法获取焦点问题

作者: 二十五_0415 | 来源:发表于2019-07-22 13:53 被阅读0次

在遇到这个问题的第一反应是有什么元素附在了input的框上了(因为以前遇到过元素覆盖导致的鼠标点击无效问题),但是在将input框的z-index增大之后仍然未解决。

尝试通过bing搜了一下select2无法获取焦点的问题,看到了两种解决办法。

  1. 把页面中的 tabindex="-1" 删掉
  2. $.fn.modal.Constructor.prototype.enforceFocus = function() {};

但是两个方法都说得不明确,然后再官方文档中找到了答案.

解决办法是这个

<div id="myModal" class="modal fade" tabindex="-1" role="dialog" aria-hidden="true">
    ...
    <select id="mySelect2">
        ...
    </select>
    ...
</div>

...

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

造成的原因也说明了,bootstrap的模态框会窃取模态框之外的焦点,而select2的下拉菜单是附在body元素(模态框之外)上的。
所以配置dropdownParent就行了,亲自试了一下确实有效。而且不一定指定模态框,指定form元素我也亲自试了没问题。

至于这个方法

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

一定要看清楚是在模态框初始化之前执行

相关文章

网友评论

      本文标题:select2在bootstrap模态框无法获取焦点问题

      本文链接:https://www.haomeiwen.com/subject/khailctx.html