Use jQuery to hide a DIV when the user clicks outside of it

后端 未结 30 3437
庸人自扰
庸人自扰 2020-11-21 04:28

I am using this code:

$(\'body\').click(function() {
   $(\'.form_wrapper\').hide();
});

$(\'.form_wrapper\').click(function(event){
   event.stopPropagatio         


        
30条回答
  •  感情败类
    2020-11-21 05:11

    A solution without jQuery for the most popular answer:

    document.addEventListener('mouseup', function (e) {
        var container = document.getElementById('your container ID');
    
        if (!container.contains(e.target)) {
            container.style.display = 'none';
        }
    }.bind(this));
    

    MDN: https://developer.mozilla.org/en/docs/Web/API/Node/contains

提交回复
热议问题