jQuery:点击DIV本身以外的任何地方关闭DIV?

Cod*_*key 16 javascript jquery

我有一个div,当点击一个按钮时向下滑动,我想在用户时向上滑动div:

  1. 点击除DIV本身之外的其他地方
  2. 单击div中的关闭按钮.

目前我已经进入了一个阶段,你点击了一个带有类的元素.panel-tab- 它用ID向下滑动面板#panel...点击它滑动的任何地方....

到目前为止,这是我的代码,以便打开和关闭DIV:

<script type="text/javascript">
$(document).ready(function(){

$('.panel-tab').click(function(e) {
  $("#panel").stop(true, true).slideToggle("slow");
  e.stopPropagation();
});

$("body").click(function () {
  $("#panel:visible").stop(true, true).slideUp("slow");
});});
</script>
Run Code Online (Sandbox Code Playgroud)

jAn*_*ndy 20

您可以将click事件绑定到该事件document并检查Click事件是否发生在该div子事件或任何子事件中.如果没有,请关闭它.

插件时间!

(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));
Run Code Online (Sandbox Code Playgroud)

用法:

$('.panel-tab').outside('click', function() {
    $('#panel').stop(true, true).slideUp('slow');
});
Run Code Online (Sandbox Code Playgroud)


Rok*_*jan 6

编辑 如何创建自定义模式弹出窗口 - 以及如何在其外部单击它关闭它


这里只是我的一个例子:http://jsbin.com/uqiver/1/edit

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

或者您也可以先检查它是否可见:

var $pan = $('#panel');

$("body").on('click', function(ev) {
    if ($pan.is(':visible') && ev.target.id !== 'panel') $pan.hide();
});
Run Code Online (Sandbox Code Playgroud)