简体   繁体   English

使用jQuery在区域外单击时隐藏div

[英]Hide div when click outside the area with jQuery

I would like to hide div content when clicking outside of it. 我想在其外部单击时隐藏div内容。 I read a lot of topics on the subject but I can't make it work. 我读了很多关于该主题的主题,但是无法使它起作用。

Here is the div I want to hide : 这是我要隐藏的div

<div class="menu_content">
    <div class="container-fluid">
        <div class="container">
            <div class="row">
                <div class="col-lg-4">
                    <h1>Title</h1>
                </div>
                <div class="col-lg-4">
                    <h1>Title</h1>
                </div>      
                <div class="col-lg-4">
                    <h1>Title</h1>
                </div>
            </div>  <!-- END ROW-->
        </div>
    </div><!-- END CONTAINER FLUID-->
</div>

I'm not an expert in Javascript, so if you have simple sample code to achieve this, it could be great. 我不是Java语言方面的专家,因此,如果您有简单的示例代码来实现这一目标,那就太好了。

I tried the following code but it does not work : 我尝试了以下代码,但它不起作用:

$(document).click(function() {
    if($(this) != $(".menu_main_content")) {
        $(".menu_main_content").hide();
    }
});

Here is the html of the code that opens the DIV content : 这是打开DIV内容的代码的html:

 <div class="menu_main_button">
        <img href=""src="{{ asset('images/icons/icon_menu_home.png') }}"  alt="" />
</div>

The button opens the DIV with .menu_main_content class. 该按钮使用.menu_main_content类打开DIV。

So the fact of clicking on the button is considered as outside the DIV. 因此,单击按钮的事实被认为是在DIV之外。 That's my problem. 那是我的问题。

Thanks in advance for your help 在此先感谢您的帮助

This is probably one for e.stopPropagation : 这可能是e.stopPropagation

Demo 演示版

$(document).click(function(e) {

  $('.menu_content').hide();
});

$('.menu_content').click(function(e) {

  e.stopPropagation();
});

$(this) always refers to document and I think you can't compare elements like that. $(this)始终引用document ,我认为您无法比较这样的元素。 Try checking if the given element is hovered, if not, hide it: 尝试检查给定元素是否悬停,如果没有,请将其隐藏:

$(document).click(function() {
    if (!$(".menu_main_content").is(":hover")) {
        $(".menu_main_content").hide();
    }
});

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

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