关闭Bootstrap-select/Select2的自动聚焦

3

http://www.bootply.com/YAQrE52K6X

    $("#dataCombo").selectpicker({
    multiple:true
    });

    <div class="container">

  <h3>Multiple Select</h3>
  <select id="dataCombo" class="selectpicker" data-live-search="true" multiple="multiple" style="width:400px;">

    <option value="one">One</option>
    <option value="two">Two</option>
    <option value="three">Three</option>
    <option value="four">Four</option>
    <option value="five">Five</option>
    <option value="six">Six</option>
  </select>

</div>

我希望关闭自动对焦,这样在点击下拉菜单后输入框不会立即要求我搜索。尝试使用.blur等方法...但目前没有任何进展。寻找解决方法。由于存在相同问题,因此转而使用“bootstrap-select”而非“select2”。设备上的键盘似乎覆盖了多个下拉项。


你想禁用允许搜索的输入框,还是只是不希望它自动聚焦? - Dekel
没有自动聚焦 - 我仍然想使用搜索框,但不希望在单击下拉菜单时立即出现。这将防止键盘立即在设备上出现。 - Tom Rudge
2个回答

3

我无法通过bootstrap-select解决这个问题(似乎他们在触发show.bs.selectshown.bs.select事件方面存在一些问题),但由于您也提到了尝试使用select2,这里是针对select2的解决方案:

  $("#dataCombo").select2({
    closeOnSelect: false
  });
  $("#dataCombo").on('select2:open', function () {
    $(document.activeElement).blur()
  });

请看这个例子:
https://jsfiddle.net/yw61h28z/

更新 - 2016/12/05

终于成功了(花了一些时间来调整焦点/模糊/目标等问题)。

$(document).ready(function() {
  $("#dataCombo").select2({
    closeOnSelect: false
  });
  $("#dataCombo").one('select2:open', function (e) {
    $(document.activeElement).blur()
  });
  $("#dataCombo").on('select2:close', function(e) {
    if ($(event.target).parents('.select2').length) {
      // The closing was done inside the select2 container
    } else {
      $("#dataCombo").one('select2:open', function (e) {
        $(document.activeElement).blur()
      });
    }
  });
});

这是我原始jsfiddle的更新版本:
https://jsfiddle.net/yw61h28z/4/ 代码背后的想法:
1. 第一次打开select2时 - 失焦输入框(仅一次)- 这确保了select2菜单已打开,但输入框没有焦点(因此不会显示键盘)。
2. 关闭select2菜单时 - 检查导致关闭的元素。
2.1. 如果该元素是select2块的一部分 - 忽略它并继续关闭菜单。
2.2. 否则 - 下一次打开select2菜单时,我们再次失焦输入框(仅一次)。

感谢您上面的回答。它存在一个小问题,就是当您现在想使用搜索时,在失去焦点之前只能输入1个字符,因为选择在键入时打开并触发模糊。对于您创建的fiddle有什么修复的想法吗? - Tom Rudge

0

对于Bootstrap Select Picker,您可以像这样操作,它对我有效:

$(document).on("change","select.selectpicker",function(){
    $(this).next().next().children(".bs-searchbox").children("input[type='search']").blur()
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接