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

当用户在DIV之外单击时,使用jQuery隐藏DIV,jquery,html,hide,styling,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

我正在使用以下代码:

$('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中有链接,当单击时链接不再工作。

您可能希望检查为主体触发的单击事件的目标,而不是依赖StopRopagation

比如:

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

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

您最好执行以下操作:

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();
    });
});
var close = true;

$(function () {

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

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


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

});

像这样的东西不管用吗

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

});


将解决方案更新为:

  • 改用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');
    }
});
即使是斯莱克:

$("html").click(function(){ 
    $(".wrapper:visible").hide();
});
.blur()
标记更有效。例如:

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

您可以做的是将单击事件绑定到文档,如果单击了下拉列表之外的内容,该事件将隐藏下拉列表,但如果单击了下拉列表内部的内容,则不会隐藏下拉列表,因此您的“显示”事件(或slidedown或任何显示下拉列表的内容)

然后在隐藏它时,解除单击事件的绑定

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

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

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

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

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

如果您在ios上遇到问题,mouseup在apple设备上不起作用

我用这个:

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

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

下面是我在另一个线程上找到的一个JSFIDLE,它也可以使用esc键:

p
是元素名称。其中还可以传递id、类或元素名。

可在桌面和移动设备上使用

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

我是这样做的:

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();
    });
});
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]);
如果(!((e.clientX>obj.x&&e.clientX obj.y&&e.clientY单击返回false。表单包装器:

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

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

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

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

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

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

选中单击区域不在目标元素或其子元素中

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

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

(只是补充prc322的答案。)

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

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

var exclude_div=$(“#ExcludedDiv”);;
$(文档)。单击(函数(e){
如果(!exclude_div.is(e.target))//如果target div不是要排除的,则添加隐藏的类
$(.myDiv1”).addClass(“隐藏”);

});
您可以将
tabindex
设置为父级
并收听
聚焦输出
事件,而不是每次单击DOM来隐藏一个特定元素

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

因此,您的HTML将如下所示:

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

不带jQuery的解决方案用于:


MDN:

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

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';
    }
   }
})
var-boxArray=[“第一个元素的id”、“第二个元素的id”、“第n个元素的id”];
window.addEventListener('mouseup',函数(事件){
对于(var i=0;i
基于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);
    }
  });
}
这增加了一些东西

  • 放置在带有“unlimited”参数的回调函数中
  • 添加了对jquery的.off()的调用,该调用与事件命名空间配对,以在事件运行后从文档中解除绑定
  • 包括用于移动功能的touchend
  • 我希望这对某人有帮助!

    $(文档).ready(函数(){
    $('.modal container')。在('click',函数(e)上{
    如果(e.target==$(此)[0]){
    $(this.removeClass('active');//或hide()
    }
    });
    });
    .modal容器{
    显示:无;
    证明内容:中心;
    对齐项目:居中;
    位置:绝对位置;
    排名:0;
    左:0;
    右:0;
    底部:0;
    背景色:rgba(0,0,0,0.5);
    z指数:999;
    }
    .modal-container.active{
    显示器:flex;
    }
    .莫代尔{
    宽度:50%;
    高度:自动;
    利润率:20px;
    填充:20px;
    背景色:#fff;
    }
    
    同一天,我们要为精英们祈祷,为我们祈祷,为我们祈祷,为我们祈祷,为我们祈祷,为我们祈祷,为我们祈祷,为我们祈祷,为我们祈祷,为我们祈祷,为我们祈祷


    这么多答案,一定是有通过权才添加了一个。。。 我没有看到当前(jQuery 3.1.1)的答案-因此:

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

    现场演示


    是的,现在链接起作用了!但是由于某种原因,当我点击链接时,我
    $(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();
        }
    });
    
    <div class="form_wrapper" tabindex="0">
        <a class="agree" href="javascript:;">I Agree</a>
        <a class="disagree" href="javascript:;">Disagree</a>
    </div>
    
    $('.form_wrapper').on('focusout', function(event){
        $('.form_wrapper').hide();
    });
    
    document.addEventListener('mouseup', function (e) {
        var container = document.getElementById('your container ID');
    
        if (!container.contains(e.target)) {
            container.style.display = 'none';
        }
    }.bind(this));
    
    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';
        }
       }
    })
    
    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);
        }
      });
    }
    
    $(function() {
        $('body').on('mouseup', function() {
            $('#your-selector').hide();
        });
    });
    
    $(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");
            }
        })
    })