我有以下功能来打开叠加菜单:
$('.context-switch').click(function() {
$(".context-switch-menu").toggle();
});
要隐藏菜单,我希望用户能够点击“.context-switch-menu”
之外的任何区域。我正在尝试:不是()但没有成功..
答案 0 :(得分:1)
这可能是困难的原因是因为事件冒泡。
您可以尝试这样的事情:
$('.context-switch').click(function(e) {
e.stopPropagation();
$(".context-switch-menu").toggle();
});
$(".context-switch-menu").click(function(e){
e.stopPropagation();
});
$("body").click(function(e){
$(".context-switch-menu").hide();
});
e.stopPropagation()
阻止click
事件冒泡到body
处理程序。没有它,任何点击.context-switch
或.context-switch-menu
也会触发你不想要的身体事件处理程序,因为它会使.context-switch
点击的效果在一半时间内无效。 (即,如果状态被隐藏,然后您单击以显示,则事件将冒泡并触发body
处理程序,然后再次隐藏.context-switch-menu
。)
答案 1 :(得分:1)
$('body').click(function(e) {
if ($(e.target).hasClass('context-switch')) {
return;
}
$(".context-switch-menu").hide();
});
$('.context-switch').click(function() {
$(".context-switch-menu").toggle();
return false;
});
答案 2 :(得分:0)
试试这个,我们不想在单击元素本身时调用函数,而不是在单击元素内部时调用函数。这就是为什么我们需要2次检查。
您想使用e.target
这是您点击的元素。
$("html").click(function(e){
if( !$(e.target).is(".context-switch-menu") &&
$(e.target).closest(".context-switch-menu").length == 0
)
{
alert("CLICKED OUTSIDE");
}
});
答案 3 :(得分:0)
没有测试,这样的工作会起作用吗?:
$('.context-switch').click(function() {
$(".context-switch-menu").show();
});
$(document).click(function() {
$(".context-switch-menu").hide();
});
而不是使用document
,'html'
或'body'
也可以使用。
答案 4 :(得分:0)
$(document).on('click', function(e) {
if (e.target.className !='context-switch-menu') {
$(".context-switch-menu").hide();
}
});
答案 5 :(得分:0)
这里只是一个想法,基于其他人过去的建议:
$(document).click(function(e){
//this should give you the clicked element's id attribute
var elem = $(e.target).attr('classname');
if(elem !== 'context-switch-menu'){
$('.context-switch-menu').slideUp('slow');
//or however you want to hide it
}
});