Javascript jQuery - 单击外部 div 后隐藏 div 菜单
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3544134/
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
jQuery - Hide a div menu after clicking outside div
提问by Simon
I've build a drop down menu at:
我在以下位置建立了一个下拉菜单:
http://www.ourbridalsongs.com/new_header/header.php
http://www.ourbridalsongs.com/new_header/header.php
When you click on the up/down arrow next to the logo - the menu appears - I'd like to make it disappear when clicking anywhere else on the screen - for some reason it's getting stuck and doesn't slide back up.
当您单击徽标旁边的向上/向下箭头时 - 菜单出现 - 我想让它在单击屏幕上的任何其他地方时消失 - 由于某种原因,它被卡住并且不会向上滑动。
Can anyone help resolve this!
任何人都可以帮助解决这个问题!
Here's my script:
这是我的脚本:
$(document).ready(function () {
$("ul.subnav").parent().append("<span></span>");
$("ul.topnav li span").click(function () {
$(this).parent().find("ul.subnav").slideDown('slow').show();
$(this).parent().click(function () {}, function () {
$(this).parent().find("ul.subnav").slideUp('slow');
});
}).hover(function () {
$(this).addClass("subhover");
}, function () {
$(this).removeClass("subhover");
});
});
Thanks!!!
谢谢!!!
采纳答案by rob waminal
add this snippet in your code
在您的代码中添加此代码段
$(document).click(function(e){
var myTarget = $(".subnav");
var clicked = e.target.className;
if($.trim(myTarget) != '') {
if($("." + myTarget) != clicked) {
$("ul.subnav").slideUp('slow').hide();
}
}
});
this will close your ul.subnavwhen you click anywhere in your document.
ul.subnav当您单击文档中的任意位置时,这将关闭您的。
回答by Crozin
It's quite simple: bind a function that hides that menu to everything except that menu. To do that bind a clicklistener to the bodyelement as it's everywhere, also bind a clicklistener to menu - the last one should just prevent from executing the first one.
这很简单:将隐藏该菜单的函数绑定到除该菜单之外的所有内容。要做到这一点,将点击侦听器绑定到body元素,因为它无处不在,还将点击侦听器绑定到菜单 - 最后一个应该阻止执行第一个。
$("body").click(function() {
$("#services-container-id").hide();
});
$("#services-container-id").click(function(e) {
e.stopPropagation();
});

