单击外部菜单以在 jquery 中关闭
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2868582/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Click outside menu to close in jquery
提问by George
So I have a drop-down menu that shows on a click, as per business requirements. The menu becomes hidden again after you mouse away from it.
所以我有一个下拉菜单,可以根据业务需求点击显示。将鼠标移开后,菜单将再次隐藏。
But now I am being asked to have it stay in place until user clicks anywhere on the document. How can this be accomplished?
但是现在我被要求让它保持原位,直到用户单击文档上的任何地方。如何做到这一点?
This is a simplified version of what I have now:
这是我现在拥有的简化版本:
$(document).ready(function() {
$("ul.opMenu li").click(function(){
$('#MainOptSubMenu',this).css('visibility', 'visible');
});
$("ul.opMenu li").mouseleave(function(){
$('#MainOptSubMenu',this).css('visibility', 'hidden');
});
});
<ul class="opMenu">
<li id="footwo" class="">
<span id="optImg" style="display: inline-block;"> <img src="http://localhost.vmsinfo.com:8002/insight/images/options-hover2.gif"/> </span>
<ul id="MainOptSubMenu" style="visibility: hidden; top: 25px; border-top: 0px solid rgb(217, 228, 250); background-color: rgb(217, 228, 250); padding-bottom: 15px;">
<li>some</li>
<li>nav</li>
<li>links</li>
</ul>
</li>
</ul>
I tried something like this $('document[id!=MainOptSubMenu]').click(function()
thinking it would trigger on anything that wasnt the menu, but it didnt work.
我试过这样的事情,$('document[id!=MainOptSubMenu]').click(function()
认为它会触发任何不是菜单的东西,但它没有用。
回答by Jon W
Take a look at the approach this question used:
看看这个问题使用的方法:
How do I detect a click outside an element?
Attach a click event to the document body which closes the window. Attach a separate click event to the window which stops propagation to the document body.
将单击事件附加到关闭窗口的文档正文。将单独的单击事件附加到窗口,以停止传播到文档正文。
$('html').click(function() {
//Hide the menus if visible
});
$('#menucontainer').click(function(event){
event.stopPropagation();
});
回答by adriendenat
The answer is right, but it will add a listener that will be triggered every time a click occurs on your page. To avoid that, you can add the listener for just one time :
答案是正确的,但它会添加一个侦听器,每次在您的页面上发生点击时都会触发该侦听器。为避免这种情况,您可以只添加一次侦听器:
$('a#menu-link').on('click', function(e) {
e.preventDefault();
e.stopPropagation();
$('#menu').toggleClass('open');
$(document).one('click', function closeMenu (e){
if($('#menu').has(e.target).length === 0){
$('#menu').removeClass('open');
} else {
$(document).one('click', closeMenu);
}
});
});
Edit: if you want to avoid the stopPropagation()
on the initial button you can use this
编辑:如果你想避免stopPropagation()
在初始按钮上你可以使用这个
var $menu = $('#menu');
$('a#menu-link').on('click', function(e) {
e.preventDefault();
if (!$menu.hasClass('active')) {
$menu.addClass('active');
$(document).one('click', function closeTooltip(e) {
if ($menu.has(e.target).length === 0 && $('a#menu-link').has(e.target).length === 0) {
$menu.removeClass('active');
} else if ($menu.hasClass('active')) {
$(document).one('click', closeTooltip);
}
});
} else {
$menu.removeClass('active');
}
});
回答by Subliminal Hash
回答by Code Commander
The stopPropagation
options are bad because they can interfere with other event handlers including other menus that might have attached close handlers to the HTML element.
这些stopPropagation
选项很糟糕,因为它们会干扰其他事件处理程序,包括其他可能将关闭处理程序附加到 HTML 元素的菜单。
Here is a simple solution based on user2989143's answer:
这是一个基于user2989143的回答的简单解决方案:
$('html').click(function(event) {
if ($(event.target).closest('#menu-container, #menu-activator').length === 0) {
$('#menu-container').hide();
}
});
回答by DA.
2 options that you can investigate:
您可以调查的 2 个选项:
- On showing of the menu, place a large empty DIV behind it covering up the rest of the page and give that an on-click event to close the menu (and itself). This is akin to the methods used with lightboxes where clicking on the background closes the lightbox
- On showing of the menu, attach a one-time click event handler on the body that closes the menu. You use jQuery's '.one()' for this.
- 在显示菜单时,在它后面放置一个大的空白 DIV,覆盖页面的其余部分,并提供一个点击事件来关闭菜单(及其本身)。这类似于使用灯箱的方法,点击背景会关闭灯箱
- 在显示菜单时,在关闭菜单的主体上附加一个一次性单击事件处理程序。为此,您可以使用 jQuery 的 '.one()'。
回答by cat5dev
I found a variant of Grsmto's solutionand Dennis' solutionfixed my issue.
我找到了Grsmto 解决方案的变体,而Dennis 的解决方案解决了我的问题。
$(".MainNavContainer").click(function (event) {
//event.preventDefault(); // Might cause problems depending on implementation
event.stopPropagation();
$(document).one('click', function (e) {
if(!$(e.target).is('.MainNavContainer')) {
// code to hide menus
}
});
});
回答by Namish
I have recently faced the same issue. I wrote the following code:
我最近遇到了同样的问题。我写了以下代码:
$('html').click(function(e) {
var a = e.target;
if ($(a).parents('.menu_container').length === 0) {
$('.ofSubLevelLinks').removeClass('active'); //hide menu item
$('.menu_container li > img').hide(); //hide dropdown image, if any
}
});
It has worked for me perfectly.
它对我很有效。
回答by user2989143
I use this solution with multiple elements with the same behavior in the same page:
我将此解决方案与同一页面中具有相同行为的多个元素一起使用:
$("html").click(function(event){
var otarget = $(event.target);
if (!otarget.parents('#id_of element').length && otarget.attr('id')!="id_of element" && !otarget.parents('#id_of_activator').length) {
$('#id_of element').hide();
}
});
stopPropagation() is a bad idea, this breaks standard behaviour of many things, including buttons and links.
stopPropagation() 是个坏主意,这打破了许多东西的标准行为,包括按钮和链接。
回答by cgfix
what about this?
那这个呢?
$(this).mouseleave(function(){
var thisUI = $(this);
$('html').click(function(){
thisUI.hide();
$('html').unbind('click');
});
});
回答by Abhimaan
even i came across the same situation and one of my mentor put this idea across to myself.
即使我遇到了同样的情况,我的一位导师也把这个想法告诉了我自己。
step:1when clicked on the button on which we should show the drop down menu. then add the below class name "more_wrap_background" to the current active page like shown below
步骤:1单击我们应该显示下拉菜单的按钮时。然后将下面的类名“more_wrap_background”添加到当前活动页面,如下所示
$('.ui-page-active').append("<div class='more_wrap_background' id='more-wrap-bg'> </div>");
step-2then add a clicks for the div tag like
步骤 2然后为 div 标签添加一个点击,如
$(document).on('click', '#more-wrap-bg', hideDropDown);
where hideDropDown is the function to be called to hide drop down menu
其中 hideDropDown 是要调用以隐藏下拉菜单的函数
Step-3and important step while hiding the drop down menu is that remove that class you that added earlier like
隐藏下拉菜单的第 3 步也是重要的一步是删除您之前添加的类
$('#more-wrap-bg').remove();
I am removing by using its id in the above code
我在上面的代码中使用它的 id 删除
.more_wrap_background {
top: 0;
padding: 0;
margin: 0;
background: rgba(0, 0, 0, 0.1);
position: fixed;
display: block;
width: 100% !important;
z-index: 999;//should be one less than the drop down menu's z-index
height: 100% !important;
}