我正在使用这段代码:

$('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 内有链接,当单击它们时它们不再起作用。

有帮助吗?

解决方案

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

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

其他提示

你最好选择这样的东西:

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

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

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

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

类似的东西:

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

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

现场演示

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

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

<强>更新

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

现场演示

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

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

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

将解决方案更新为:

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

没有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 /文档/网络/ API /节点/包含

使用 ESC 功能实时演示

适用于桌面和移动设备

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

不会有这样的工作吗?

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

});

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

});

甚至更加沉稳:

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

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

您可以将tabindex设置为父<div>并听取focusout事件。

,而不是每次点击DOM来隐藏一个特定元素。

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

所以你的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();
});

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

基于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. 添加了对jquery的.off()的调用,该调用与事件命名空间配对,以便在文档运行后从文档中解除绑定。
  3. 包含移动功能的touchend
  4. 我希望这有助于某人!

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

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

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

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

在jquery中为mpad工作mousedown / mouseup?

我用这个:

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

          if (container.has(e.target).length === 0)
          {
              container.hide();
          }
      });
 $('body').click(function(event) {
    if (!$(event.target).is('p'))
    {
        $("#e2ma-menu").hide();
    }
});

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

如果单击.form_wrapper:

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

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

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

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

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

(只需添加prc322的答案。)

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

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

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

$(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>

https://sdtuts.com/click-on-not-复制指定元件/

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

$(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");
        }
    })
})
我是这样做的:

var close = true;

$(function () {

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

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


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

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

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

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

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

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

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

您可以做的是将单击事件绑定到文档,如果单击下拉列表中的内容,则会隐藏下拉列表,但如果单击下拉列表中的内容,则不会隐藏它,因此您的<!> quot; show <!> QUOT;事件(或滑动或其他任何显示下拉列表)

    $('.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');
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top