当用户单击它的外部时,使用jQuery隐藏一个DIV。

时间:2022-08-26 19:58:18

I am using this code:

我正在使用这段代码:

$('body').click(function() {
   $('.form_wrapper').hide();
});

$('.form_wrapper').click(function(event){
   event.stopPropagation();
});

And this HTML:

这个HTML:

<div class="form_wrapper">
   <a class="agree" href="javascript:;">I Agree</a>
   <a class="disagree" href="javascript:;">Disagree</a>
</div>

The problem is that I have links inside the DIV and when they no longer work when clicked.

问题是,我在DIV中有链接,当它们在单击时不再工作。

33 个解决方案

#1


2211  

Had the same problem, came up with this easy solution. It's even working recursive:

有同样的问题,想出了这个简单的解决办法。甚至工作递归:

$(document).mouseup(function(e) 
{
    var container = $("YOUR CONTAINER SELECTOR");

    // if the target of the click isn't the container nor a descendant of the container
    if (!container.is(e.target) && container.has(e.target).length === 0) 
    {
        container.hide();
    }
});

#2


193  

You'd better go with something like this:

你最好带点这样的东西:

var mouse_is_inside = false;

$(document).ready(function()
{
    $('.form_content').hover(function(){ 
        mouse_is_inside=true; 
    }, function(){ 
        mouse_is_inside=false; 
    });

    $("body").mouseup(function(){ 
        if(! mouse_is_inside) $('.form_wrapper').hide();
    });
});

#3


63  

You might want to check the target of the click event that fires for the body instead of relying on stopPropagation.

您可能想要检查单击事件的目标,而不是依赖于停止传播。

Something like:

喜欢的东西:

$("body").click
(
  function(e)
  {
    if(e.target.className !== "form_wrapper")
    {
      $(".form_wrapper").hide();
    }
  }
);

Also, the body element may not include the entire visual space shown in the browser. If you notice that your clicks are not registering, you may need to add the click handler for the HTML element instead.

另外,body元素可能不包括浏览器中显示的整个视觉空间。如果您注意到您的单击没有注册,您可能需要为HTML元素添加单击处理程序。

#4


58  

This code detects any click event on the page and then hides the #CONTAINER element if and only if the element clicked was neither the #CONTAINER element nor one of its descendants.

此代码检测页面上的任何单击事件,然后隐藏#CONTAINER元素,如果且仅当单击的元素既不是#容器元素,也不是它的一个子代。

$(document).on('click', function (e) {
    if ($(e.target).closest("#CONTAINER").length === 0) {
        $("#CONTAINER").hide();
    }
});

#5


21  

Live DEMO

现场演示

Check click area is not in the targeted element or in it's child

检查单击区域不在目标元素中或在它的子元素中。

$(document).click(function (e) {
    if ($(e.target).parents(".dropdown").length === 0) {
        $(".dropdown").hide();
    }
});

UPDATE:

更新:

jQuery stop propagation is the best solution

jQuery停止传播是最好的解决方案。

Live DEMO

现场演示

$(".button").click(function(e){
    $(".dropdown").show();
     e.stopPropagation();
});

$(".dropdown").click(function(e){
    e.stopPropagation();
});

$(document).click(function(){
    $(".dropdown").hide();
});

#6


17  

$(document).click(function(event) {
    if ( !$(event.target).hasClass('form_wrapper')) {
         $(".form_wrapper").hide();
    }
});

#7


15  

Updated the solution to:

更新的解决方案:

  • use mouseenter and mouseleave instead
  • 使用mouseenter和mouseleave代替。
  • of hover use live event binding
  • 悬停使用事件绑定。

var mouseOverActiveElement = false;

var mouseOverActiveElement = false;

$('.active').live('mouseenter', function(){
    mouseOverActiveElement = true; 
}).live('mouseleave', function(){ 
    mouseOverActiveElement = false; 
});
$("html").click(function(){ 
    if (!mouseOverActiveElement) {
        console.log('clicked outside active element');
    }
});

#8


10  

A solution without jQuery for the most popular answer:

一个没有jQuery的解决方案:

document.addEventListener('mouseup', function (e) {
    var container = document.getElementById('your container ID');

    if (!container.contains(e.target)) {
        container.style.display = 'none';
    }
}.bind(this));

MDN: https://developer.mozilla.org/en/docs/Web/API/Node/contains

MDN:https://developer.mozilla.org/en/docs/Web/API/Node/contains

#9


7  

Live demo with ESC functionality

现场演示与ESC功能。

Works on both Desktop and Mobile

在桌面和移动端都可以工作。

var notH = 1,
    $pop = $('.form_wrapper').hover(function(){ notH^=1; });

$(document).on('mousedown keydown', function( e ){
  if(notH||e.which==27) $pop.hide();
});

If for some case you need to be sure that your element is really visible when you do clicks on the document: if($pop.is(':visible') && (notH||e.which==27)) $pop.hide();

如果在某些情况下,您需要确保当您在文档上单击时,您的元素是真正可见的:If ($pop.is(':visible') && (notH|| . ==27)) $pop.hide();

#10


6  

Wouldn't something like this work?

像这样的工作不行吗?

$("body *").not(".form_wrapper").click(function() {

});

or

$("body *:not(.form_wrapper)").click(function() {

});

#11


4  

Even sleaker:

甚至溶化:

$("html").click(function(){ 
    $(".wrapper:visible").hide();
});

#12


4  

And for Touch devices like IPAD and IPHONE we can use following code

对于像IPAD和IPHONE这样的触摸设备,我们可以使用以下代码。

$(document).on('touchstart', function (event) {
var container = $("YOUR CONTAINER SELECTOR");

if (!container.is(e.target) // if the target of the click isn't the container...
&& container.has(e.target).length === 0) // ... nor a descendant of the container
    {
        container.hide();
    }
});

#13


4  

Here's a jsfiddle I found on another thread, works with esc key also: http://jsfiddle.net/S5ftb/404

这是我在另一个线程上找到的一个jsfiddle,它与esc键一起工作:http://jsfiddle.net/S5ftb/404。

    var button = $('#open')[0]
    var el     = $('#test')[0]

    $(button).on('click', function(e) {
      $(el).show()
      e.stopPropagation()
    })

    $(document).on('click', function(e) {
      if ($(e.target).closest(el).length === 0) {
        $(el).hide()
      }
    })

    $(document).on('keydown', function(e) {
      if (e.keyCode === 27) {
        $(el).hide()
      }
    })

#14


4  

Built off of prc322's awesome answer.

建立在prc322的可怕的答案。

function hideContainerOnMouseClickOut(selector, callback) {
  var args = Array.prototype.slice.call(arguments); // Save/convert arguments to array since we won't be able to access these within .on()
  $(document).on("mouseup.clickOFF touchend.clickOFF", function (e) {
    var container = $(selector);

    if (!container.is(e.target) // if the target of the click isn't the container...
        && container.has(e.target).length === 0) // ... nor a descendant of the container
    {
      container.hide();
      $(document).off("mouseup.clickOFF touchend.clickOFF");
      if (callback) callback.apply(this, args);
    }
  });
}

This adds a couple things...

这增加了一些东西…

  1. Placed within a function with a callback with "unlimited" args
  2. 放置在一个函数中,带有“无限”args的回调函数。
  3. Added a call to jquery's .off() paired with a event namespace to unbind the event from the document once it's been run.
  4. 添加了对jquery .off()的调用,并与事件名称空间结合,以便在文档运行后将事件从文档中释放出来。
  5. Included touchend for mobile functionality
  6. 包括移动功能的touchend。

I hope this helps someone!

我希望这能帮助别人!

#15


2  

var n = 0;
$("#container").mouseenter(function() {
n = 0;

}).mouseleave(function() {
n = 1;
});

$("html").click(function(){ 
if (n == 1) {
alert("clickoutside");
}
});

#16


2  

if you have trouble with ios, mouseup is not working on apple device.

如果你在ios上遇到麻烦,mouseup并没有在苹果设备上工作。

does mousedown /mouseup in jquery work for the ipad?

在jquery中mousedown /mouseup是否适用于ipad?

i use this:

我用这个:

$(document).bind('touchend', function(e) {
        var container = $("YOURCONTAINER");

          if (container.has(e.target).length === 0)
          {
              container.hide();
          }
      });

#17


2  

 $('body').click(function(event) {
    if (!$(event.target).is('p'))
    {
        $("#e2ma-menu").hide();
    }
});

p is the element name. Where one can pass the id or class or element name also.

p是元素名。也可以通过id或类或元素名。

#18


2  

Return false if you click on .form_wrapper:

返回false,如果您点击。form_wrapper:

$('body').click(function() {
  $('.form_wrapper').click(function(){
  return false
});
   $('.form_wrapper').hide();
});

//$('.form_wrapper').click(function(event){
//   event.stopPropagation();
//});

#19


2  

Instead of listening to every single click on the DOM to hide one specific element, you could set tabindex to the parent <div> and listen to the focusout events.

您可以将tabindex设置为parent

,并监听focusout事件,而不是侦听DOM中的每一个单击,以隐藏一个特定的元素。

Setting tabindex will make sure that the blur event is fired on the <div> (normally it wouldn't).

设置tabindex将确保在

(正常情况下不会)触发模糊事件。

So your HTML would look like:

你的HTML看起来是这样的:

<div class="form_wrapper" tabindex="0">
    <a class="agree" href="javascript:;">I Agree</a>
    <a class="disagree" href="javascript:;">Disagree</a>
</div>

And your JS:

和你的JS:

$('.form_wrapper').on('focusout', function(event){
    $('.form_wrapper').hide();
});

#20


2  

$(document).ready(function() {
	$('.modal-container').on('click', function(e) {
	  if(e.target == $(this)[0]) {
		$(this).removeClass('active'); // or hide()
	  }
	});
});
.modal-container {
	display: none;
	justify-content: center;
	align-items: center;
	position: absolute;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background-color: rgba(0,0,0,0.5);
	z-index: 999;
}

.modal-container.active {
    display: flex;  
}

.modal {
	width: 50%;
	height: auto;
	margin: 20px;
	padding: 20px;
	background-color: #fff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="modal-container active">
	<div class="modal">
		<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean ac varius purus. Ut consectetur viverra nibh nec maximus. Nam luctus ligula quis arcu accumsan euismod. Pellentesque imperdiet volutpat mi et cursus. Sed consectetur sed tellus ut finibus. Suspendisse porttitor laoreet lobortis. Nam ut blandit metus, ut interdum purus.</p>
	</div>
</div>

#21


1  

i did it like this:

我这样做了:

var close = true;

$(function () {

    $('body').click (function(){

        if(close){
            div.hide();
        }
        close = true;
    })


alleswasdenlayeronclicknichtschliessensoll.click( function () {   
        close = false;
    });

});

#22


1  

dojo.query(document.body).connect('mouseup',function (e)
{
    var obj = dojo.position(dojo.query('div#divselector')[0]);
    if (!((e.clientX > obj.x && e.clientX <(obj.x+obj.w)) && (e.clientY > obj.y && e.clientY <(obj.y+obj.h))) ){
        MyDive.Hide(id);
    }
});

#23


1  

Attach a click event to top level elements outside the form wrapper, for example:

将单击事件附加到表单包装器外部的顶层元素,例如:

$('#header, #content, #footer').click(function(){
    $('.form_wrapper').hide();
});

This will also work on touch devices, just make sure you don't include a parent of .form_wrapper in your list of selectors.

这也适用于触摸设备,只需要确保在选择器列表中不包含.form_wrapper的父元素。

#24


1  

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js">
</script>
<script>
$(document).ready(function(){
  $("#hide").click(function(){
    $("p").hide();
  });
  $("#show").click(function(){
    $("p").show();
  });
});
</script>
</head>
<body>
<p>If you click on the "Hide" button, I will disappear.</p>
<button id="hide">Hide</button>
<button id="show">Show</button>
</body>
</html>

#25


1  

I wanted to like the most-voted for suggestion, but it didn't work for me.

我想要最喜欢的建议,但它对我不起作用。

This method is nearly the same but worked for me. http://www.codesynthesis.co.uk/code-snippets/use-jquery-to-hide-a-div-when-the-user-clicks-outside-of-it

这种方法几乎是一样的,但对我有效。http://www.codesynthesis.co.uk/code-snippets/use-jquery-to-hide-a-div-when-the-user-clicks-outside-of-it

#26


1  

(Just adding on to prc322's answer.)

(只是增加了prc322的答案。)

In my case I'm using this code to hide a navigation menu that appears when the user clicks an appropriate tab. I found it was useful to add an extra condition, that the target of the click outside the container is not a link.

在我的例子中,我使用这个代码来隐藏一个导航菜单,当用户单击一个适当的选项卡时出现。我发现添加一个额外的条件是有用的,在容器外点击的目标不是一个链接。

$(document).mouseup(function (e)
{
    var container = $("YOUR CONTAINER SELECTOR");

    if (!$("a").is(e.target) // if the target of the click isn't a link ...
        && !container.is(e.target) // ... or the container ...
        && container.has(e.target).length === 0) // ... or a descendant of the container
    {
        container.hide();
    }
});

This is because some of the links on my site add new content to the page. If this new content is added at the same time that the navigation menu disappears it might be disorientating for the user.

这是因为我网站上的一些链接向页面添加了新内容。如果在导航菜单消失的同时添加了这个新内容,那么用户可能会迷失方向。

#27


1  

var exclude_div = $("#ExcludedDiv");;  
$(document).click(function(e){
   if( !exclude_div.is( e.target ) )  // if target div is not the one you want to exclude then add the class hidden
        $(".myDiv1").addClass("hidden");  

}); 

FIDDLE

小提琴

#28


1  

By using this code you can hide as many items as you want

通过使用此代码,您可以隐藏任意多的项。

var boxArray = ["first element's id","second element's id","nth element's id"];
   window.addEventListener('mouseup', function(event){
   for(var i=0; i < boxArray.length; i++){
    var box = document.getElementById(boxArray[i]);
    if(event.target != box && event.target.parentNode != box){
        box.style.display = 'none';
    }
   }
})

#29


0  

What you can do is bind a click event to the document that will hide the dropdown if something outside the dropdown is clicked, but won't hide it if something inside the dropdown is clicked, so your "show" event (or slidedown or whatever shows the dropdown)

你所能做的是将一个点击事件绑定到文档中,如果在下拉列表之外的东西被点击,就会隐藏掉下拉列表,但是如果点击下拉菜单中的某个东西,就不会隐藏它,所以你的“show”事件(或者是slidedown或者其他显示下拉列表的东西)

    $('.form_wrapper').show(function(){

        $(document).bind('click', function (e) {
            var clicked = $(e.target);
            if (!clicked.parents().hasClass("class-of-dropdown-container")) {
                 $('.form_wrapper').hide();
            }
        });

    });

Then when hiding it, unbind the click event

然后在隐藏它时,取消绑定单击事件。

$(document).unbind('click');

#30


0  

According to the docs, .blur() works for more than the <input> tag. For example:

根据文档,.blur()的作用大于 <输入> 标记。例如:

$('.form_wrapper').blur(function(){
   $(this).hide();
});

#1


2211  

Had the same problem, came up with this easy solution. It's even working recursive:

有同样的问题,想出了这个简单的解决办法。甚至工作递归:

$(document).mouseup(function(e) 
{
    var container = $("YOUR CONTAINER SELECTOR");

    // if the target of the click isn't the container nor a descendant of the container
    if (!container.is(e.target) && container.has(e.target).length === 0) 
    {
        container.hide();
    }
});

#2


193  

You'd better go with something like this:

你最好带点这样的东西:

var mouse_is_inside = false;

$(document).ready(function()
{
    $('.form_content').hover(function(){ 
        mouse_is_inside=true; 
    }, function(){ 
        mouse_is_inside=false; 
    });

    $("body").mouseup(function(){ 
        if(! mouse_is_inside) $('.form_wrapper').hide();
    });
});

#3


63  

You might want to check the target of the click event that fires for the body instead of relying on stopPropagation.

您可能想要检查单击事件的目标,而不是依赖于停止传播。

Something like:

喜欢的东西:

$("body").click
(
  function(e)
  {
    if(e.target.className !== "form_wrapper")
    {
      $(".form_wrapper").hide();
    }
  }
);

Also, the body element may not include the entire visual space shown in the browser. If you notice that your clicks are not registering, you may need to add the click handler for the HTML element instead.

另外,body元素可能不包括浏览器中显示的整个视觉空间。如果您注意到您的单击没有注册,您可能需要为HTML元素添加单击处理程序。

#4


58  

This code detects any click event on the page and then hides the #CONTAINER element if and only if the element clicked was neither the #CONTAINER element nor one of its descendants.

此代码检测页面上的任何单击事件,然后隐藏#CONTAINER元素,如果且仅当单击的元素既不是#容器元素,也不是它的一个子代。

$(document).on('click', function (e) {
    if ($(e.target).closest("#CONTAINER").length === 0) {
        $("#CONTAINER").hide();
    }
});

#5


21  

Live DEMO

现场演示

Check click area is not in the targeted element or in it's child

检查单击区域不在目标元素中或在它的子元素中。

$(document).click(function (e) {
    if ($(e.target).parents(".dropdown").length === 0) {
        $(".dropdown").hide();
    }
});

UPDATE:

更新:

jQuery stop propagation is the best solution

jQuery停止传播是最好的解决方案。

Live DEMO

现场演示

$(".button").click(function(e){
    $(".dropdown").show();
     e.stopPropagation();
});

$(".dropdown").click(function(e){
    e.stopPropagation();
});

$(document).click(function(){
    $(".dropdown").hide();
});

#6


17  

$(document).click(function(event) {
    if ( !$(event.target).hasClass('form_wrapper')) {
         $(".form_wrapper").hide();
    }
});

#7


15  

Updated the solution to:

更新的解决方案:

  • use mouseenter and mouseleave instead
  • 使用mouseenter和mouseleave代替。
  • of hover use live event binding
  • 悬停使用事件绑定。

var mouseOverActiveElement = false;

var mouseOverActiveElement = false;

$('.active').live('mouseenter', function(){
    mouseOverActiveElement = true; 
}).live('mouseleave', function(){ 
    mouseOverActiveElement = false; 
});
$("html").click(function(){ 
    if (!mouseOverActiveElement) {
        console.log('clicked outside active element');
    }
});

#8


10  

A solution without jQuery for the most popular answer:

一个没有jQuery的解决方案:

document.addEventListener('mouseup', function (e) {
    var container = document.getElementById('your container ID');

    if (!container.contains(e.target)) {
        container.style.display = 'none';
    }
}.bind(this));

MDN: https://developer.mozilla.org/en/docs/Web/API/Node/contains

MDN:https://developer.mozilla.org/en/docs/Web/API/Node/contains

#9


7  

Live demo with ESC functionality

现场演示与ESC功能。

Works on both Desktop and Mobile

在桌面和移动端都可以工作。

var notH = 1,
    $pop = $('.form_wrapper').hover(function(){ notH^=1; });

$(document).on('mousedown keydown', function( e ){
  if(notH||e.which==27) $pop.hide();
});

If for some case you need to be sure that your element is really visible when you do clicks on the document: if($pop.is(':visible') && (notH||e.which==27)) $pop.hide();

如果在某些情况下,您需要确保当您在文档上单击时,您的元素是真正可见的:If ($pop.is(':visible') && (notH|| . ==27)) $pop.hide();

#10


6  

Wouldn't something like this work?

像这样的工作不行吗?

$("body *").not(".form_wrapper").click(function() {

});

or

$("body *:not(.form_wrapper)").click(function() {

});

#11


4  

Even sleaker:

甚至溶化:

$("html").click(function(){ 
    $(".wrapper:visible").hide();
});

#12


4  

And for Touch devices like IPAD and IPHONE we can use following code

对于像IPAD和IPHONE这样的触摸设备,我们可以使用以下代码。

$(document).on('touchstart', function (event) {
var container = $("YOUR CONTAINER SELECTOR");

if (!container.is(e.target) // if the target of the click isn't the container...
&& container.has(e.target).length === 0) // ... nor a descendant of the container
    {
        container.hide();
    }
});

#13


4  

Here's a jsfiddle I found on another thread, works with esc key also: http://jsfiddle.net/S5ftb/404

这是我在另一个线程上找到的一个jsfiddle,它与esc键一起工作:http://jsfiddle.net/S5ftb/404。

    var button = $('#open')[0]
    var el     = $('#test')[0]

    $(button).on('click', function(e) {
      $(el).show()
      e.stopPropagation()
    })

    $(document).on('click', function(e) {
      if ($(e.target).closest(el).length === 0) {
        $(el).hide()
      }
    })

    $(document).on('keydown', function(e) {
      if (e.keyCode === 27) {
        $(el).hide()
      }
    })

#14


4  

Built off of prc322's awesome answer.

建立在prc322的可怕的答案。

function hideContainerOnMouseClickOut(selector, callback) {
  var args = Array.prototype.slice.call(arguments); // Save/convert arguments to array since we won't be able to access these within .on()
  $(document).on("mouseup.clickOFF touchend.clickOFF", function (e) {
    var container = $(selector);

    if (!container.is(e.target) // if the target of the click isn't the container...
        && container.has(e.target).length === 0) // ... nor a descendant of the container
    {
      container.hide();
      $(document).off("mouseup.clickOFF touchend.clickOFF");
      if (callback) callback.apply(this, args);
    }
  });
}

This adds a couple things...

这增加了一些东西…

  1. Placed within a function with a callback with "unlimited" args
  2. 放置在一个函数中,带有“无限”args的回调函数。
  3. Added a call to jquery's .off() paired with a event namespace to unbind the event from the document once it's been run.
  4. 添加了对jquery .off()的调用,并与事件名称空间结合,以便在文档运行后将事件从文档中释放出来。
  5. Included touchend for mobile functionality
  6. 包括移动功能的touchend。

I hope this helps someone!

我希望这能帮助别人!

#15


2  

var n = 0;
$("#container").mouseenter(function() {
n = 0;

}).mouseleave(function() {
n = 1;
});

$("html").click(function(){ 
if (n == 1) {
alert("clickoutside");
}
});

#16


2  

if you have trouble with ios, mouseup is not working on apple device.

如果你在ios上遇到麻烦,mouseup并没有在苹果设备上工作。

does mousedown /mouseup in jquery work for the ipad?

在jquery中mousedown /mouseup是否适用于ipad?

i use this:

我用这个:

$(document).bind('touchend', function(e) {
        var container = $("YOURCONTAINER");

          if (container.has(e.target).length === 0)
          {
              container.hide();
          }
      });

#17


2  

 $('body').click(function(event) {
    if (!$(event.target).is('p'))
    {
        $("#e2ma-menu").hide();
    }
});

p is the element name. Where one can pass the id or class or element name also.

p是元素名。也可以通过id或类或元素名。

#18


2  

Return false if you click on .form_wrapper:

返回false,如果您点击。form_wrapper:

$('body').click(function() {
  $('.form_wrapper').click(function(){
  return false
});
   $('.form_wrapper').hide();
});

//$('.form_wrapper').click(function(event){
//   event.stopPropagation();
//});

#19


2  

Instead of listening to every single click on the DOM to hide one specific element, you could set tabindex to the parent <div> and listen to the focusout events.

您可以将tabindex设置为parent

,并监听focusout事件,而不是侦听DOM中的每一个单击,以隐藏一个特定的元素。

Setting tabindex will make sure that the blur event is fired on the <div> (normally it wouldn't).

设置tabindex将确保在

(正常情况下不会)触发模糊事件。

So your HTML would look like:

你的HTML看起来是这样的:

<div class="form_wrapper" tabindex="0">
    <a class="agree" href="javascript:;">I Agree</a>
    <a class="disagree" href="javascript:;">Disagree</a>
</div>

And your JS:

和你的JS:

$('.form_wrapper').on('focusout', function(event){
    $('.form_wrapper').hide();
});

#20


2  

$(document).ready(function() {
	$('.modal-container').on('click', function(e) {
	  if(e.target == $(this)[0]) {
		$(this).removeClass('active'); // or hide()
	  }
	});
});
.modal-container {
	display: none;
	justify-content: center;
	align-items: center;
	position: absolute;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background-color: rgba(0,0,0,0.5);
	z-index: 999;
}

.modal-container.active {
    display: flex;  
}

.modal {
	width: 50%;
	height: auto;
	margin: 20px;
	padding: 20px;
	background-color: #fff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="modal-container active">
	<div class="modal">
		<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean ac varius purus. Ut consectetur viverra nibh nec maximus. Nam luctus ligula quis arcu accumsan euismod. Pellentesque imperdiet volutpat mi et cursus. Sed consectetur sed tellus ut finibus. Suspendisse porttitor laoreet lobortis. Nam ut blandit metus, ut interdum purus.</p>
	</div>
</div>

#21


1  

i did it like this:

我这样做了:

var close = true;

$(function () {

    $('body').click (function(){

        if(close){
            div.hide();
        }
        close = true;
    })


alleswasdenlayeronclicknichtschliessensoll.click( function () {   
        close = false;
    });

});

#22


1  

dojo.query(document.body).connect('mouseup',function (e)
{
    var obj = dojo.position(dojo.query('div#divselector')[0]);
    if (!((e.clientX > obj.x && e.clientX <(obj.x+obj.w)) && (e.clientY > obj.y && e.clientY <(obj.y+obj.h))) ){
        MyDive.Hide(id);
    }
});

#23


1  

Attach a click event to top level elements outside the form wrapper, for example:

将单击事件附加到表单包装器外部的顶层元素,例如:

$('#header, #content, #footer').click(function(){
    $('.form_wrapper').hide();
});

This will also work on touch devices, just make sure you don't include a parent of .form_wrapper in your list of selectors.

这也适用于触摸设备,只需要确保在选择器列表中不包含.form_wrapper的父元素。

#24


1  

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js">
</script>
<script>
$(document).ready(function(){
  $("#hide").click(function(){
    $("p").hide();
  });
  $("#show").click(function(){
    $("p").show();
  });
});
</script>
</head>
<body>
<p>If you click on the "Hide" button, I will disappear.</p>
<button id="hide">Hide</button>
<button id="show">Show</button>
</body>
</html>

#25


1  

I wanted to like the most-voted for suggestion, but it didn't work for me.

我想要最喜欢的建议,但它对我不起作用。

This method is nearly the same but worked for me. http://www.codesynthesis.co.uk/code-snippets/use-jquery-to-hide-a-div-when-the-user-clicks-outside-of-it

这种方法几乎是一样的,但对我有效。http://www.codesynthesis.co.uk/code-snippets/use-jquery-to-hide-a-div-when-the-user-clicks-outside-of-it

#26


1  

(Just adding on to prc322's answer.)

(只是增加了prc322的答案。)

In my case I'm using this code to hide a navigation menu that appears when the user clicks an appropriate tab. I found it was useful to add an extra condition, that the target of the click outside the container is not a link.

在我的例子中,我使用这个代码来隐藏一个导航菜单,当用户单击一个适当的选项卡时出现。我发现添加一个额外的条件是有用的,在容器外点击的目标不是一个链接。

$(document).mouseup(function (e)
{
    var container = $("YOUR CONTAINER SELECTOR");

    if (!$("a").is(e.target) // if the target of the click isn't a link ...
        && !container.is(e.target) // ... or the container ...
        && container.has(e.target).length === 0) // ... or a descendant of the container
    {
        container.hide();
    }
});

This is because some of the links on my site add new content to the page. If this new content is added at the same time that the navigation menu disappears it might be disorientating for the user.

这是因为我网站上的一些链接向页面添加了新内容。如果在导航菜单消失的同时添加了这个新内容,那么用户可能会迷失方向。

#27


1  

var exclude_div = $("#ExcludedDiv");;  
$(document).click(function(e){
   if( !exclude_div.is( e.target ) )  // if target div is not the one you want to exclude then add the class hidden
        $(".myDiv1").addClass("hidden");  

}); 

FIDDLE

小提琴

#28


1  

By using this code you can hide as many items as you want

通过使用此代码,您可以隐藏任意多的项。

var boxArray = ["first element's id","second element's id","nth element's id"];
   window.addEventListener('mouseup', function(event){
   for(var i=0; i < boxArray.length; i++){
    var box = document.getElementById(boxArray[i]);
    if(event.target != box && event.target.parentNode != box){
        box.style.display = 'none';
    }
   }
})

#29


0  

What you can do is bind a click event to the document that will hide the dropdown if something outside the dropdown is clicked, but won't hide it if something inside the dropdown is clicked, so your "show" event (or slidedown or whatever shows the dropdown)

你所能做的是将一个点击事件绑定到文档中,如果在下拉列表之外的东西被点击,就会隐藏掉下拉列表,但是如果点击下拉菜单中的某个东西,就不会隐藏它,所以你的“show”事件(或者是slidedown或者其他显示下拉列表的东西)

    $('.form_wrapper').show(function(){

        $(document).bind('click', function (e) {
            var clicked = $(e.target);
            if (!clicked.parents().hasClass("class-of-dropdown-container")) {
                 $('.form_wrapper').hide();
            }
        });

    });

Then when hiding it, unbind the click event

然后在隐藏它时,取消绑定单击事件。

$(document).unbind('click');

#30


0  

According to the docs, .blur() works for more than the <input> tag. For example:

根据文档,.blur()的作用大于 <输入> 标记。例如:

$('.form_wrapper').blur(function(){
   $(this).hide();
});