简体   繁体   English

单击背景div时关闭div

[英]Close div when clicking Background div

I want to close a Div when i click on the Background div(SearchBlur). 当我单击Background div(SearchBlur)时,我想关闭一个Div。 My problem is if i click on the shown div it closes also. 我的问题是,如果我单击显示的div,它也会关闭。

here is my javascrip code 这是我的javascrip代码

SearchBlur.addEventListener('click', closePopup);

function closePopup(){

   if(counter == 1){
        $( "#search_input" ).animate({ "left": "-=300px"}, "normal" );
        $('.SearchBlur').fadeOut("normal");
        counter = 0;
    }

}

here my html 这是我的html

<div class="SearchBlur" id="SB_Back">
    <div class="div_container" id="container">
        <div class="grid_div">
            <div id="gridwrapper">
            </div>
        </div>
    </div>
</div>

the Programm looks like this 程序看起来像这样 在此处输入图片说明

i want to close the popup wehn i click on the dark background 我想关闭弹出窗口,因为我单击深色背景

sorry for my bad english :D 对不起,我的英语不好:D

尝试使用以下代码将侦听器添加到子div中

event.stopPropagation();

Use event.stopPropagation(); 使用event.stopPropagation(); onclick the child you want onclick您想要的孩子

 var counter = 1; $( ".SearchBlur" ).on( "click", function() { if(counter == 1){ $( "#search_input" ).animate({ "left": "-300px"}, "normal" ); $('.SearchBlur').fadeOut("normal"); counter = 0; } }); $( ".div_container" ).on( "click", function() { event.stopPropagation(); }); 
 .SearchBlur{ background:blue; } .div_container{ width:100px; background:red; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="SearchBlur" id="SB_Back"> <div class="div_container" id="container"> <div class="grid_div"> <div id="gridwrapper">div_container </div> </div> </div> </div> 

Which div are you trying to close? 您要关闭哪个div?

From what I can see, you're fading out the highest level div, so all markup nested within SearchBlur will also be hidden. 据我所知,您正在淡出最高级别的div,因此嵌套在SearchBlur中的所有标记也将被隐藏。 I assume you want to target a deeper nested div, for example: 我假设您想定位更深层的div,例如:

function closePopup(){
   if(counter == 1){
        $( "#search_input" ).animate({ "left": "-=300px"}, "normal" );
        $('.div_container').fadeOut("normal");
        counter = 0;
    }
}

In a simple way your html looks like: 用简单的方式,您的html看起来像:

<div class="blur">
    <div class="popup"></div>
</div>

Your JS is just like this: 您的JS就像这样:

$('.blur').on('click', function (e){
  if (e.target === this)
    $(this).fadeOut();
});

Here is codepen: https://codepen.io/alexmoronto/pen/xaKvxg 这是codepen: https ://codepen.io/alexmoronto/pen/xaKvxg

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM