Close a div by clicking outside

前端 未结 7 1007
感情败类
感情败类 2020-11-27 06:05

I want to hide a div by clicking on the close link in it, or by clicking anywhere outside that div.

I am trying following code, it opens and close t

7条回答
  •  野性不改
    2020-11-27 06:50

    I'd suggest using the stopPropagation() method as shown in the modified fiddle:

    Fiddle

    $('body').click(function() {
        $(".popup").hide();
    });
    
    $('.popup').click(function(e) {
        e.stopPropagation();
    });
    

    That way you can hide the popup when you click on the body, without having to add an extra if, and when you click on the popup, the event doesn't bubble up to the body by going through the popup.

提交回复
热议问题