我有一个“下拉菜单”的 HTML 项目,其结构如下...
<li class="ui-dropdown-list" >
<a href="#">Right Drop Down Menu</a>
<ul>
<li><a href="#">Item</a></li>
<li><a href="#">Item</a></li>
<li><a href="#">Item</a></li>
</ul>
</li>
使用 jQuery 将其设为下拉列表,代码如下。
jQuery.fn.dropdown = function () {
var defaults = {
button: null,
menu: null,
visible: false
};
var options = $.extend(defaults, options);
return this.each(function () {
options.button = $(this);
options.menu = $(this).find("ul");
// when the parent is clicked, determine whether dropdown needs to occur
options.button.click(function () {
options.visible ? lift(options.menu) : drop(options.menu);
options.visible = !options.visible;
});
// drop the menu down so that it can be seen.
function drop(e) {
options.button.addClass("open");
options.menu.show();
}
// lift the menu up, hiding it from view.
function lift(e) {
options.menu.hide();
options.button.removeClass('open');
}
});
};
我正在尝试将其连接起来,以便如果用户单击菜单之外的任何位置,它就会折叠菜单。事实证明这比我预想的要困难得多。甚至尝试使用页面级事件。有什么建议么?
菜单本身从未真正“接收”焦点,因此使用 .blur 似乎不适合该目的。
最佳答案
您可以在这里使用事件冒泡来发挥自己的优势,如果click
事件一直冒泡到document
,则关闭菜单,如果它发生在菜单中,请停止气泡,以便 document
上的处理程序不会被命中,如下所示:
jQuery.fn.dropdown = function () {
var defaults = {
button: null,
menu: null,
visible: false
};
var options = $.extend(defaults, options);
return this.each(function () {
options.button = $(this);
options.menu = $(this).find("ul");
$(document).click(lift); //close on bubble!
options.button.click(function (e) {
options.menu.is(':visible') ? lift() : drop();
e.stopPropagation(); //prevent bubble!
});
function drop(e) {
options.button.addClass("open");
options.menu.show();
}
function lift(e) {
options.menu.hide();
options.button.removeClass('open');
}
});
};
关于jquery .blur 用于整个 HTML block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2925848/