当用户使用jQuery单击DIV时隐藏DIV [英] Hide a DIV when the user clicks outside of it using jQuery

查看:70
本文介绍了当用户使用jQuery单击DIV时隐藏DIV的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下代码:

$(document).ready(function(){
    $(".SlideDiv").hide();
    $(".Show_hide").show();

    $('.Show_hide').click(function(){
        $(".SlideDiv").slideToggle();
    });
});

此HTML:

    <a href="#" class="Show_hide">Show/hide</a>
<div class="SlideDiv">this is content page
<a class="agree" href="https://www.google.com/" target="_blank">google</a>
</div>

这个CSS:

.SlideDiv
{  
    height:200px;
    background-color:gray;
    margin-top:10px;

}
.Show_hide
{
    display:none;
}

问题是我在DIV中有链接,当他们单击该链接时,打开但显示功能没有隐藏.

The problem is that I have links inside the DIV and when they click that link open but show function didn't hide.

演示

推荐答案

演示

DEMO

无需为此使用任何插件.您只需要将对文档的每次单击绑定到一个函数,并检查单击对象是否不是任何功能链接. event.stopPropagation() 用于防止事件冒泡.

No need to use any plugins for this. You just need to bind every click on the document to a function and check if the click was on an object is not any of the functional links. event.stopPropagation() is used to prevent bubbling of events.

$(document).ready(function(){
    $(document).on('click',function(e){
        if( !$(e.target).is('.Show_hide, .SlideDiv') || 		
            !$(e.target).parents('.Show_hide, .SlideDiv').length == 0){
            $(".SlideDiv").slideUp();
            e.stopPropagation();
        }
    });
    $(".SlideDiv").hide();
    $(".Show_hide").show();

    $('.Show_hide').click(function(){
        $(".SlideDiv").slideToggle();
    });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<a href="#" class="Show_hide">Show/hide</a>
<div class="SlideDiv">this is content page
<a class="agree" href="https://www.google.com/" target="_blank">google</a>
</div>

这篇关于当用户使用jQuery单击DIV时隐藏DIV的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆