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

后端 未结 30 3448
庸人自扰
庸人自扰 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:04

    Here's a jsfiddle I found on another thread, works with esc key also: http://jsfiddle.net/S5ftb/404

        var button = $('#open')[0]
        var el     = $('#test')[0]
    
        $(button).on('click', function(e) {
          $(el).show()
          e.stopPropagation()
        })
    
        $(document).on('click', function(e) {
          if ($(e.target).closest(el).length === 0) {
            $(el).hide()
          }
        })
    
        $(document).on('keydown', function(e) {
          if (e.keyCode === 27) {
            $(el).hide()
          }
        })
    

提交回复
热议问题