简体   繁体   English

检测用户何时在div外部单击

[英]Detecting when a user clicks outside a div

I'm showing the user a modal/lightbox. 我正在向用户显示模态/灯箱。 The modal shows up and the rest of the page goes dim when the user clicks a button. 当用户单击按钮时,模式显示,页面的其余部分变暗。 Usual stuff. 通常的东西。

However I want to do this. 但是我想这样做。 If the user clicks any element outside of the modal, I want the modal to go away and the page to return to normal. 如果用户点击模态之外的任何元素,我希望模态消失,页面恢复正常。

How can this be done? 如何才能做到这一点? I know I can set an onclick event for body, and then check if event target is my modal, but what if the user clicks on a link/textbox/button within the modal? 我知道我可以为body设置一个onclick事件,然后检查事件目标是否是我的模态,但如果用户点击模态中的链接/文本框/按钮会怎么样? In that case, target won't be the modal. 在这种情况下,目标将不是模态。 How can I solve this? 我怎么解决这个问题?

Is there a way to check if the event target is contained with <div id="modal"></div> , so if it is, I won't close the modal, and if not, that means user clicked outside the modal and I can close it? 有没有办法检查事件目标是否包含在<div id="modal"></div> ,所以如果是,我将不会关闭模态,如果没有,这意味着用户点击模态外我可以关闭它吗?

jsBin demo jsBin演示

$(document).mouseup(function(e){
   if(e.target.id !== 'modal' ){
     $('#modal').hide();
   }
});

$('#modal').mouseup(function(e){
  e.stopPropagation();  // prevent mouseup propagate to underneath layers
});

你可以在填充整个空间的模态下放置一个div,并将你的点击处理程序附加到它。

$("body").click(function(e){
    if( ! $(e.target).closest("#modal").length ){
        $('#modal').hide();
    }
});

demo 演示

Another one approach: 另一种方法:

var mouseOverModal = false;

$(document).click(function(e){
   if ( ! mouseOverModal ){
       // close modal
   }
});

$('#modal').bind("mouseenter mouseleave", function(e){
     mouseOverModal = ( "mouseenter" == e.type );
})

$('#open-modal-handler').click(function(){  
    // open modal  
    return false; // <- IMPORTANT
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM