关闭后模糊Select2输入

时间:2014-01-16 08:53:54

标签: javascript jquery jquery-select2

我希望select2元素在触发select2-close事件时失去焦点,到目前为止我尝试过的是:

.on("select2-close", function (e) {
    var $focused = $(':focus');
    $focused.blur();
});

以及一些变体可以获得像document.activeElement,$(e.target)这样的重点元素。

JSFiddle

2 个答案:

答案 0 :(得分:10)

您需要从包含分隔符中删除.select2-container-active类:

.on("select2-close", function () {
    setTimeout(function() {
        $('.select2-container-active').removeClass('select2-container-active');
        $(':focus').blur();
    }, 1);
});

我在这里使用setTimeout作为一种hacky方式,以确保在插件本身完成关闭后触发此操作。

JSFiddle demo

答案 1 :(得分:0)

我阅读了select2.jsSelect2 4.0.6-rc.1)的代码。

问题是,当您有2个(或更多)select2框并且我们打开其中一个框时。在不关闭其下拉菜单的情况下,我们尝试打开第二个框的下拉菜单。然后,触发第二个框的open事件。 open事件处理程序本身会触发彼此的close事件下拉列表。

打开下拉菜单时会调用它。 可以在第1508行中找到: 请继续阅读我在摘要中所做的评论

$(document.body).on('mousedown.select2.' + container.id, function (e) {
  var $target = $(e.target);

  /**
   * Get the current box
   */
  var $select = $target.closest('.select2');

  /**
   * Get all opened boxes
   */
  var $all = $('.select2.select2-container--open');

  $all.each(function () {
    // [...]

    /**
     * Don't do the following for the current box
     */
    if (this == $select[0]) {
      return;
    }

    // [...]

    /**
     * The close event is triggered to close all opened boxes.
     * So far, that makes sense.
     */
    $element.select2('close');
  });
});

然后close事件处理程序本身为关闭框设置焦点吗? 我认为这里是错误行为的产生。

1467行中,我发现关闭下拉菜单时的行为,并且将设置焦点:

container.on('close', function () {
  // [...]

  /**
   * This must be done for opening and not for closing boxes, isn't it?
   */
  self.$selection.focus();
  window.setTimeout(function () {
    self.$selection.focus();
  }, 0);

  // [...]
});

当我在以下几行中注释掉时,搜索字段的焦点便随心所欲。

// self.$selection.focus();
// window.setTimeout(function () {
//   self.$selection.focus();
// }, 0);

但是为什么我们要设置将要关闭的元素的焦点? 如何在不更改select2.js中的代码的情况下实现此行为?