当用户在其外部单击时,使用jQuery隐藏DIV

时间:2009-09-10 06:11:27

标签: jquery html hide styling

我正在使用此代码:

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

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

这个HTML:

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

问题是我在DIV中有链接,当点击时它们不再有效。

37 个答案:

答案 0 :(得分:2380)

遇到同样的问题,提出了这个简单的解决方案。它甚至可以递归工作:

$(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();
    }
});

答案 1 :(得分:199)

你最好选择这样的东西:

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();
    });
});

答案 2 :(得分:73)

此代码检测页面上的任何点击事件,然后隐藏#CONTAINER元素,当且仅当点击的元素既不是#CONTAINER元素也不是其后代之一。

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

答案 3 :(得分:72)

您可能想要检查为身体触发的点击事件的目标,而不是依赖于stopPropagation。

类似的东西:

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

此外,主体元素可能不包括浏览器中显示的整个可视空间。如果您注意到您的点击未注册,则可能需要添加HTML元素的点击处理程序。

答案 4 :(得分:30)

Live DEMO

检查点击区域不在目标元素或其子级

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

<强>更新

jQuery停止传播是最佳解决方案

Live DEMO

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

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

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

答案 5 :(得分:18)

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

答案 6 :(得分:16)

将解决方案更新为:

  • 使用mouseenter和mouseleave代替
  • 悬停使用实时事件绑定

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');
    }
});

答案 7 :(得分:12)

没有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

答案 8 :(得分:8)

Live demo with ESC functionality

适用于桌面和移动设备

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

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

如果在某些情况下,您需要确保在点击文档时确实可以看到您的元素:if($pop.is(':visible') && (notH||e.which==27)) $pop.hide();

答案 9 :(得分:6)

不会有这样的工作吗?

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

});

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

});

答案 10 :(得分:4)

您可以将tabindex设置为父<div>并听取focusout事件,而不是收听DOM上的每次点击以隐藏一个特定元素。

设置tabindex将确保在blur上触发<div>事件(通常不会)。

所以你的HTML看起来像是:

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

你的JS:

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

答案 11 :(得分:4)

对于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();
    }
});

答案 12 :(得分:4)

这是我在另一个帖子上找到的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()
      }
    })

答案 13 :(得分:4)

基于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);
    }
  });
}

这增加了几件事......

  1. 放置在具有“无限”args
  2. 回调的函数中
  3. 添加了对jquery的.off()的调用,该调用与事件命名空间配对,以便在文档运行后从文档中解除绑定。
  4. 包含移动功能的touchend
  5. 我希望这有助于某人!

答案 14 :(得分:4)

甚至更加沉稳:

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

答案 15 :(得分:2)

如果您遇到ios问题,那么mouseup无法在Apple设备上运行。

does mousedown /mouseup in jquery work for the ipad?

我用这个:

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

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

答案 16 :(得分:2)

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

p是元素名称。其中一个人也可以传递id或类或元素名称。

答案 17 :(得分: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>

答案 18 :(得分:2)

如果单击.form_wrapper:

,则返回false
$('body').click(function() {
  $('.form_wrapper').click(function(){
  return false
});
   $('.form_wrapper').hide();
});

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

答案 19 :(得分:2)

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

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

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

答案 20 :(得分:2)

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

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

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

答案 21 :(得分:2)

(只需添加到prc322&#39的答案。)

在我的情况下,我使用此代码隐藏了当用户点击相应标签时显示的导航菜单。我发现添加额外条件非常有用,即容器外部点击的目标是而不是链接。

$(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();
    }
});

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

答案 22 :(得分:1)

通过使用此代码,您可以隐藏任意数量的项目

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';
    }
   }
})

答案 23 :(得分:1)

这么多的答案,必须是一个增加一个的通行权...... 我没有看到当前(jQuery 3.1.1)的答案 - 所以:

$(function() {
    $('body').on('mouseup', function() {
        $('#your-selector').hide();
    });
});

答案 24 :(得分:1)

https://sdtuts.com/click-on-not-specified-element/

复制

现场演示http://demos.sdtuts.com/click-on-specified-element

$(document).ready(function () {
    var is_specified_clicked;
    $(".specified_element").click(function () {
        is_specified_clicked = true;
        setTimeout(function () {
            is_specified_clicked = false;
        }, 200);
    })
    $("*").click(function () {
        if (is_specified_clicked == true) {
//WRITE CODE HERE FOR CLICKED ON OTHER ELEMENTS
            $(".event_result").text("you were clicked on specified element");
        } else {
//WRITE CODE HERE FOR SPECIFIED ELEMENT CLICKED
            $(".event_result").text("you were clicked not on specified element");
        }
    })
})

答案 25 :(得分: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);
    }
});

答案 26 :(得分:1)

&#13;
&#13;
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");  

}); 
&#13;
&#13;
&#13;

FIDDLE

答案 27 :(得分: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>

答案 28 :(得分:1)

我是这样做的:

var close = true;

$(function () {

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

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


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

});

答案 29 :(得分:0)

切换普通设备和触摸设备

我在这里读了一些答案并创建了一些我用作div的代码,它们起到了弹出气泡的作用。

$('#openPopupBubble').click(function(){
    $('#popupBubble').toggle();

    if($('#popupBubble').css('display') === 'block'){
        $(document).bind('mousedown touchstart', function(e){
            if($('#openPopupBubble').is(e.target) || $('#openPopupBubble').find('*').is(e.target)){
                $(this).unbind(e);
            } 
            else if(!$('#popupBubble').find('*').is(e.target)){
                $('#popupBubble').hide();
                $(this).unbind(e);
            }
        });
    }
});

您还可以使用类更加抽象,并根据触发点击事件的按钮选择正确的弹出气泡。

$('body').on('click', '.openPopupBubble', function(){
    $(this).next('.popupBubble').toggle();

    if($(this).next('.popupBubble').css('display') === 'block'){
        $(document).bind('mousedown touchstart', function(e){
            if($(this).is(e.target) || $(this).find('*').is(e.target)){
                $(this).unbind(e);
            } 
            else if(!$(this).next('.popupBubble').find('*').is(e.target)){
                $(this).next('.popupBubble').hide();
                $(this).unbind(e);
            }
        });
    }
});

答案 30 :(得分:0)

您可以做的是将单击事件绑定到文档,如果单击下拉列表中的内容,则会隐藏下拉列表,但如果单击下拉列表中的内容,则不会隐藏它,因此您的“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();
            }
        });

    });

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

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

答案 31 :(得分:0)

According to the docs.blur()的效果超过<input>标记。例如:

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

答案 32 :(得分:0)

This solution should work fine, it's easy :

jQuery(document).ready(function($) {
    jQuery(document).click(function(event) {
        if(typeof  jQuery(event.target).attr("class") != "undefined") {
            var classnottobeclickforclose = ['donotcountmeforclickclass1', 'donotcountmeforclickclass2','donotcountmeforclickclass3'];
            var arresult = jQuery.inArray(jQuery(event.target).attr("class"), classnottobeclickforclose);
            if (arresult < 0) {
                jQuery(".popup").hide();
            }
        }
    });
});

In Above code change donotcountmeforclickclass1 , donotcountmeforclickclass2 etc with classes which you have used to show popup or on it's click popup should not effect so you have to definitely add class which you are using to open popup.

Change .popup class with popup class.

答案 33 :(得分:0)

我正在研究一个搜索框,该搜索框根据处理的关键字显示自动完成功能。当我不想单击任何选项时,我将使用下面的代码隐藏处理后的列表,它可以正常工作。

$(document).click(function() {
 $('#suggestion-box').html("");
});

建议框是我的自动填充容器,在其中显示值。

答案 34 :(得分:0)

弹出窗口中使用接受的答案时,您可能会遇到一些问题。在某些情况下,点击随机位置可能会导致不必要的操作,即错误地单击按钮可能会带您进入新页面。

我不确定这是否是最有效的解决方案,但为避免这种情况,我建议使用屏幕蒙版。确保屏幕遮罩位于<body>标记的正下方,以便它可以被width:100%; height: 100%覆盖整个屏幕。另请注意,它位于所有元素之前z-index: 99如果您希望在启用屏幕遮罩时单击另一个项目或div ,只需为该项目或div分配更高的z-index

屏幕遮罩最初不显示(displayed:none),并且在单击(onclick="hidemenu()")时会调用隐藏功能。

<body>
<div class="screenmask" onclick="hidemenu()" style="position:fixed; width: 100%; height: 100%; top: 0px; right: 0px; display: none; z-index: 99;"></div>

处理“同一页面上的多个不同弹出菜单” 的javascript函数可能类似于以下内容:

<script>
// an element with onclick="showmenu('id_here')" pops a menu in the screen
function showmenu(id) {  
  var popmenu = document.getElementById(id); // assume popmenu is of class .cardmenu
  $('.cardmenu').hide();   // clear the screen from other popmenus first
  $(menu).show();          // pop the desired specific menu
  $('.screenmask').show(); // activate screenmask
}
    
function hidemenu() {      // called when clicked on the screenmask
  $('.cardmenu').hide();   // clear the screen from all the popmenus
  $('.screenmask').hide(); // deactivate screenmask
}
</script>

答案 35 :(得分:-2)

$(document).ready(function() {

$('.headings').click(function () {$('#sub1').css("display",""); });
$('.headings').click(function () {return false;});
$('#sub1').click(function () {return false;});
$('body').click(function () {$('#sub1').css("display","none");

})});

答案 36 :(得分:-3)

我认为它可以轻松得多。我是这样做的:

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