Jquery UI自动完成组合框按钮单击事件

Dav*_*bak 15 javascript jquery combobox jquery-ui jquery-autocomplete

使用jquery ui自动完成功能创建组合框时,我遇到了奇怪的行为.每当我单击滚动条滚动查看结果列表然后单击我的组合框按钮以关闭结果列表关闭结果然后再次打开.我希望它关闭菜单.

Repro的步骤

  1. 打开jsfiddle演示
  2. 在自动完成中键入"i"或按下下拉按钮.
  3. 单击垂直滚动以滚动结果
  4. 单击下拉按钮

用于创建按钮的脚本

 this.button = $("<button type='button'>&nbsp;</button>")
    .attr({ "tabIndex": -1, "title": "Show all items" })
    .insertAfter(input)
    .button({
         icons: {
             primary: "ui-icon-triangle-1-s"
         },
         text: false
    })
    .removeClass("ui-corner-all")
    .addClass("ui-corner-right ui-button-icon")
    .click(function () {

        // when i put breakpoint here, and my focus is not on input, 
        // then this if steatment is false????

        if (input.autocomplete("widget").is(":visible")) {
            input.autocomplete("close");
            return;
        }

        // work around a bug (likely same cause as #5265)
        $(this).blur();

        // pass empty string as value to search for, displaying all results
        input.autocomplete("search", "");
        input.focus();
});
Run Code Online (Sandbox Code Playgroud)

CSS(强制长结果菜单滚动)

.ui-autocomplete {
    max-height: 100px;
    overflow-y: auto;
    /* prevent horizontal scrollbar */
    overflow-x: hidden;
    /* add padding to account for vertical scrollbar */
    padding-right: 20px;
}
/* IE 6 doesn't support max-height
 * we use height instead, but this forces the menu to always be this tall
 */
* html .ui-autocomplete {
    height: 100px;
}
Run Code Online (Sandbox Code Playgroud)

即使焦点转移到小部件本身而不是输入元素,我的解决方案可能是关闭小部件?

任何想法如何修改此代码,以便它以这种方式行事?

j08*_*691 5

根据自动完成小部件的各种点击和鼠标事件的问题,我想出了这个:jsFiddle示例.

jQuery的:

var input = $('#txtComplete');

var data = [];
var isOpen = false;

function _init() {
    for (var idx = 0; idx <= 100; idx++) {
        data.push('item: ' + idx);
    };
    input.autocomplete({
        source: data,
        minLength: 0,
        open: function(event, ui) {
            isOpen = true;
        },
        select: function(event, ui) {
            isOpen = false;
        }
    });
}

function afterInit() {
    var button = $("<button type='button'>&nbsp;</button>").attr("tabIndex", -1).attr("title", "Show all items").insertAfter(input).button({
        icons: {
            primary: "ui-icon-triangle-1-s"
        },
        text: false
    }).removeClass("ui-corner-all").addClass("ui-corner-right ui-button-icon").click(function(event) {
        input.focus();
        if (isOpen) {
            input.autocomplete("close");
            isOpen = false;
        } else {
            input.autocomplete("search", "");
            event.stopImmediatePropagation();
        }
    });
}
$(window).click(function() {
    input.autocomplete("close");
    isOpen = false;
});
$(function() {
    _init();
    afterInit();
});?
Run Code Online (Sandbox Code Playgroud)