我有一些HTML菜单,当用户单击这些菜单的头部时,我会完全显示这些菜单。当用户在菜单区域外单击时,我希望隐藏这些元素。
jQuery是否可以实现这样的功能?
$("#menuscontainer").clickOutsideThisElement(function() {
// Hide the menus
});
我有一些HTML菜单,当用户单击这些菜单的头部时,我会完全显示这些菜单。当用户在菜单区域外单击时,我希望隐藏这些元素。
jQuery是否可以实现这样的功能?
$("#menuscontainer").clickOutsideThisElement(function() {
// Hide the menus
});
当前回答
这对我来说非常及时:
$('body').click(function() {
// Hide the menus if visible.
});
其他回答
我在YUI 3中是这样做的:
// Detect the click anywhere other than the overlay element to close it.
Y.one(document).on('click', function (e) {
if (e.target.ancestor('#overlay') === null && e.target.get('id') != 'show' && overlay.get('visible') == true) {
overlay.hide();
}
});
我正在检查祖先是否不是小部件元素容器,如果目标不是打开控件/元素的对象,如果我想关闭的小部件/元素已经打开(不那么重要)。
使用流中断、模糊/聚焦事件或任何其他棘手的技术,只需将事件流与元素的亲属关系匹配即可:
$(document).on("click.menu-outside", function(event){
// Test if target and it's parent aren't #menuscontainer
// That means the click event occur on other branch of document tree
if(!$(event.target).parents().andSelf().is("#menuscontainer")){
// Click outisde #menuscontainer
// Hide the menus (but test if menus aren't already hidden)
}
});
要删除事件侦听器外部的单击,只需执行以下操作:
$(document).off("click.menu-outside");
假设您想要检测用户在外部或内部单击的div是否具有id,例如:“我的特殊小部件”。
收听身体点击事件:
document.body.addEventListener('click', (e) => {
if (isInsideMySpecialWidget(e.target, "my-special-widget")) {
console.log("user clicked INSIDE the widget");
}
console.log("user clicked OUTSIDE the widget");
});
function isInsideMySpecialWidget(elem, mySpecialWidgetId){
while (elem.parentElement) {
if (elem.id === mySpecialWidgetId) {
return true;
}
elem = elem.parentElement;
}
return false;
}
在这种情况下,您不会破坏页面中某些元素的正常点击流,因为您没有使用“stopPropagation”方法。
这里的其他解决方案不适合我,所以我不得不使用:
if(!$(event.target).is('#foo'))
{
// hide menu
}
编辑:普通Javascript变体(2021-03-31)
我使用这个方法来处理在单击下拉菜单外部时关闭下拉菜单的问题。
首先,我为组件的所有元素创建了一个自定义类名。这个类名将被添加到组成菜单小部件的所有元素中。
const className = `dropdown-${Date.now()}-${Math.random() * 100}`;
我创建了一个函数来检查单击和单击元素的类名。如果clicked元素不包含我上面生成的自定义类名,它应该将show标志设置为false,菜单将关闭。
const onClickOutside = (e) => {
if (!e.target.className.includes(className)) {
show = false;
}
};
然后,我将单击处理程序附加到窗口对象。
// add when widget loads
window.addEventListener("click", onClickOutside);
……最后还有一些家政服务
// remove listener when destroying the widget
window.removeEventListener("click", onClickOutside);
我最后做了这样的事情:
$(document).on('click', 'body, #msg_count_results .close',function() {
$(document).find('#msg_count_results').remove();
});
$(document).on('click','#msg_count_results',function(e) {
e.preventDefault();
return false;
});
我在新容器中有一个关闭按钮,用于最终用户友好的UI。为了不通过,我不得不使用return false。当然,有一个A HREF带你去某个地方会很好,或者你可以调用一些ajax的东西。不管怎样,这对我来说都很好。这正是我想要的。