【问题标题】:Click events are blocked when JQuery-Select2 dropdown is open. Needs to be clicked twice to fire click event当 JQuery-Select2 下拉菜单打开时,单击事件被阻止。需要点击两次才能触发点击事件
【发布时间】:2016-09-06 10:50:41
【问题描述】:

我在一页中有一个下拉菜单和一个提交按钮。该下拉菜单是使用 JQuery-select2 3.5.3 版实现的

当 JQuery-Select2 下拉菜单打开时,单击事件被阻止。所以提交按钮需要被点击两次才能触发点击事件。

HTML

<select id="supId" style="width:300px">
  <option value=""></option>
  <option value="1">Supplier 1</option>
  <option value="2">Supplier 2</option>
  <option value="3">Supplier 3</option>
</select>
<br><br><br><br><br><br><br><br><br>
<input type="button" value="Submit" id="submitBtn" onclick="$('#dispDiv').html('Clicked');">
<br><br>
<div id="dispDiv"></div>

Javascript

$("#supId").select2({
        placeholder: "Select Supplier",
        allowClear: true
    });

在此处查看正在运行的example

下拉菜单使焦点保持打开状态,并在下拉菜单外的第一次点击中释放焦点。然后像往常一样在第二次点击中点击事件工作。

这与 Stackoverflow 中的问题 Mouse hover events are blocked 有关

如何解决这个问题?

【问题讨论】:

    标签: javascript jquery jquery-select2 select2


    【解决方案1】:

    花了几个小时搜索后,从网站Going from select2 box to another requires two clicks得到一个想法

    select2.js 中的 drop-mask 的自毁中添加如下所示的“点击转发器”几乎可以解决问题

    $(document.elementFromPoint(e.clientX,e.clientY)).trigger("click");
    $(document.elementFromPoint(e.clientX,e.clientY)).trigger("focus");
    

    详细编辑如下。

    首先找到创建下拉掩码区域(我的js中的第1557行)。这将如下所示,并在self.close(); 之后添加上述两行。

    // create the dropdown mask if doesn't already exist
    mask = $("#select2-drop-mask");
    if (mask.length === 0) {
        mask = $(document.createElement("div"));
        mask.attr("id","select2-drop-mask").attr("class","select2-drop-mask");
        mask.hide();
        mask.appendTo(this.body);
        mask.on("mousedown touchstart click", function (e) {
            // Prevent IE from generating a click event on the body
            reinsertElement(mask);
    
            var dropdown = $("#select2-drop"), self;
            if (dropdown.length > 0) {
                self=dropdown.data("select2");
                if (self.opts.selectOnBlur) {
                    self.selectHighlighted({noFocus: true});
                }
                self.close();
    
                // The following two lines are newly added
                // Adding this to forward through the mask
                $(document.elementFromPoint(e.clientX,e.clientY)).trigger("click");
                $(document.elementFromPoint(e.clientX,e.clientY)).trigger("focus");
    
                e.preventDefault();
                e.stopPropagation();
            }
        });
    }
    

    这以某种方式解决了我的问题。

    这在下拉菜单和页面上的其他元素之间非常有效,但是单击另一个下拉菜单并不能通过单击实现。

    【讨论】:

    • 添加这两行代码帮助我在使用 Select2 的旧版应用程序上解决了类似的情况,谢谢!
    猜你喜欢
    • 1970-01-01
    • 2023-03-17
    • 2014-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多