How to detect clicks outside of a css modal?

This question already has an answer here:

  • How do I detect a click outside an element? 76 answers

  • Probably the simplest way is to bind click event to body and see if it comes from the element (e.target) which has parent (walk up the tree with closest method) .modal :

    $(document).click(function(e) {
        if (!$(e.target).closest('.modal').length) {
            alert('click outside!');
        }
    });
    

    Demo: http://jsfiddle.net/c89Ls0av/4/

    By the way, overlay made with outline is an interesting idea, but it's not real overlay, as it still allows to interact with underlying page elements. Here is an example of the overlay made with div container covering entire page: http://jsfiddle.net/c89Ls0av/5/. This one will prevent page interaction when modal is visible.

    And here is an example of how open/close functionality can be use together: http://jsfiddle.net/c89Ls0av/7/.


    With the help of a javascript framework this is quite easy.

    Follow these steps:

  • Attach a click event to the document which closes or hides the modal.
  • Attach a separate click event to the window which stops click propagation.
  • Example:

    $('html').click(function(){
        $('.modal').hide();
    });
    $('.modal').click(function(e){
        e.stopPropagation();
    });
    

    http://jsfiddle.net/c89Ls0av/3/

    Warning! Stopping propagation can introduce strange behaviour


    Dfsq answer will work fine.. but if you want something to do with dialog boxes you may have a look at jQuery ui dialog boxes. It gives you many options with dialog boxes which you can configure as per your needs.

    http://jqueryui.com/dialog/

    链接地址: http://www.djcxy.com/p/83046.html

    上一篇: 在JQuery中有没有与点击事件相反的东西?

    下一篇: 如何检测外部的CSS模式点击?