jQuery: Close DIV by clicking anywhere apart from the DIV itself?

后端 未结 3 1906

I have a div that slides down when a button is clicked, and I would like to slide up the div when a user:

  1. Clicks anwhere except within the DIV itself
相关标签:
3条回答
  • 2020-12-16 14:12

    EDIT How to create a custom modal popup - and how to close it clicking outside of it


    Here, just an example of mine: http://jsbin.com/uqiver/1/edit

    $("body").on('click', function(ev) {
        var myID = ev.target.id;
        if (myID !== 'panel') {
            $('#panel').hide();
        }
    });
    

    Or you can also check if it's visible at first:

    var $pan = $('#panel');
    
    $("body").on('click', function(ev) {
        if ($pan.is(':visible') && ev.target.id !== 'panel') $pan.hide();
    });
    

    0 讨论(0)
  • 2020-12-16 14:32

    i would do something like this

    var $doc, $panel = $('.panel-tab');
    $doc = $(document);
    $doc.bind("click", function(){
       $panel.hide();
       $doc.undbind("click");
    });
    
    $panel.bind("click", function(e){
       e.stopPropagation();
    });
    

    you always close the tab on the click on the document, but you stop the event from propagation on the tab it self.

    here a working example: http://jsfiddle.net/meo/TnG4E/

    0 讨论(0)
  • 2020-12-16 14:33

    You could bind a click event to the document and check if the click event happend within that div or any children. If not, close it.

    Plugin time!

    (function($){
        $.fn.outside = function(ename, cb){
            return this.each(function(){
                var $this = $(this),
                    self = this;
    
                $(document).bind(ename, function tempo(e){
                    if(e.target !== self && !$.contains(self, e.target)){
                        cb.apply(self, [e]);
                        if(!self.parentNode) $(document.body).unbind(ename, tempo);
                    }
                });
            });
        };
    }(jQuery));
    

    usage:

    $('.panel-tab').outside('click', function() {
        $('#panel').stop(true, true).slideUp('slow');
    });
    
    0 讨论(0)
提交回复
热议问题