我有一些HTML菜单,当用户单击这些菜单的头部时,我会完全显示这些菜单。当用户在菜单区域外单击时,我希望隐藏这些元素。
jQuery是否可以实现这样的功能?
$("#menuscontainer").clickOutsideThisElement(function() {
// Hide the menus
});
我有一些HTML菜单,当用户单击这些菜单的头部时,我会完全显示这些菜单。当用户在菜单区域外单击时,我希望隐藏这些元素。
jQuery是否可以实现这样的功能?
$("#menuscontainer").clickOutsideThisElement(function() {
// Hide the menus
});
当前回答
该事件具有元素的名为event.path的属性,该属性是“以树顺序列出其所有祖先的静态有序列表”。要检查事件是否源自特定DOM元素或其子元素之一,只需检查该特定DOM元素的路径。它还可以用于通过在some函数中对元素检查进行逻辑“或”运算来检查多个元素。
$(“body”).click(函数){target=document.getElementById(“main”);flag=event.path.some(函数(el,i,arr){返回(el==目标)})if(标志){console.log(“内部”)}其他{console.log(“外部”)}});#主要的,主要的{显示:内联块;背景:黄色;}<script src=“https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js“></script><div id=“main”><ul><li>测试总管</li><li>测试总管</li><li>测试总管</li><li>测试总管</li><li>测试总管</li></ul></div><div id=“main2”>外部主管道</div>
所以你的情况应该是
$("body").click(function() {
target = $("#menuscontainer")[0];
flag = event.path.some(function(el, i, arr) {
return (el == target)
});
if (!flag) {
// Hide the menus
}
});
其他回答
$(document).click(function() {
$(".overlay-window").hide();
});
$(".overlay-window").click(function() {
return false;
});
如果单击文档,则隐藏给定元素,除非单击同一元素。
正如另一位海报所说,有很多陷阱,特别是如果你正在显示的元素(在本例中是菜单)具有交互元素。我发现以下方法相当稳健:
$('#menuscontainer').click(function(event) {
//your code that shows the menus fully
//now set up an event listener so that clicking anywhere outside will close the menu
$('html').click(function(event) {
//check up the tree of the click target to check whether user has clicked outside of menu
if ($(event.target).parents('#menuscontainer').length==0) {
// your code to hide menu
//this event listener has done its job so we can unbind it.
$(this).unbind(event);
}
})
});
这对我来说非常有效!!
$('html').click(function (e) {
if (e.target.id == 'YOUR-DIV-ID') {
//do something
} else {
//do something
}
});
尝试以下代码:
if ($(event.target).parents().index($('#searchFormEdit')) == -1 &&
$(event.target).parents().index($('.DynarchCalendar-topCont')) == -1 &&
(_x < os.left || _x > (os.left + 570) || _y < os.top || _y > (os.top + 155)) &&
isShowEditForm) {
setVisibleEditForm(false);
}
这是我解决这个问题的方法:
$(document).ready(function() {
$('#user-toggle').click(function(e) {
$('#user-nav').toggle();
e.stopPropagation();
});
$('body').click(function() {
$('#user-nav').hide();
});
$('#user-nav').click(function(e){
e.stopPropagation();
});
});