我有一些HTML菜单,当用户单击这些菜单的头部时,我会完全显示这些菜单。当用户在菜单区域外单击时,我希望隐藏这些元素。
jQuery是否可以实现这样的功能?
$("#menuscontainer").clickOutsideThisElement(function() {
// Hide the menus
});
我有一些HTML菜单,当用户单击这些菜单的头部时,我会完全显示这些菜单。当用户在菜单区域外单击时,我希望隐藏这些元素。
jQuery是否可以实现这样的功能?
$("#menuscontainer").clickOutsideThisElement(function() {
// Hide the menus
});
当前回答
$("body > div:not(#dvid)").click(function (e) {
//your code
});
其他回答
这是一个更通用的解决方案,它允许监视多个元素,并动态地从队列中添加和删除元素。
它保存一个全局队列(autoCloseQueue)——一个对象容器,用于在外部单击时应关闭的元素。
每个队列对象键都应该是DOM元素id,值应该是一个具有2个回调函数的对象:
{onPress: someCallbackFunction, onOutsidePress: anotherCallbackFunction}
将其放入文档就绪回调中:
window.autoCloseQueue = {}
$(document).click(function(event) {
for (id in autoCloseQueue){
var element = autoCloseQueue[id];
if ( ($(e.target).parents('#' + id).length) > 0) { // This is a click on the element (or its child element)
console.log('This is a click on an element (or its child element) with id: ' + id);
if (typeof element.onPress == 'function') element.onPress(event, id);
} else { //This is a click outside the element
console.log('This is a click outside the element with id: ' + id);
if (typeof element.onOutsidePress == 'function') element.onOutsidePress(event, id); //call the outside callback
delete autoCloseQueue[id]; //remove the element from the queue
}
}
});
然后,当创建id为“menuscontainer”的DOM元素时,只需将此对象添加到队列:
window.autoCloseQueue['menuscontainer'] = {onOutsidePress: clickOutsideThisElement}
要做到这一点,最广泛的方法是选择网页上的所有内容,除了不希望检测到点击的元素,并在打开菜单时绑定点击事件。
然后,当菜单关闭时,移除绑定。
使用.stopPropagation可防止事件影响菜单容器的任何部分。
$("*").not($("#menuscontainer")).bind("click.OutsideMenus", function ()
{
// hide the menus
//then remove all of the handlers
$("*").unbind(".OutsideMenus");
});
$("#menuscontainer").bind("click.OutsideMenus", function (event)
{
event.stopPropagation();
});
我在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', '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的东西。不管怎样,这对我来说都很好。这正是我想要的。
单击元素时,这将切换导航菜单。
$(document).on('click',函数(e){var elem=$(e.target).最近('#menu'),box=$(e.target).最近('#nav');if(元素长度){e.预防违约();$('#nav').tggle();}否则如果(!box.length){$('#nav').hide();}});<script src=“https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js“></script><li id=“menu”><a></a></li><ul id=“nav”><!--单击菜单时,导航将切换(在本例中它可以是一个图标)--><li class=“page”><a>第1页</a></li><li class=“page”><a>第2页</a></li><li class=“page”><a>第3页</a></li><li class=“page”><a>第4页</a></li></ul>