关于html:当用户点击DIV时,使用jQuery隐藏DIV

Use jQuery to hide a DIV when the user clicks outside of it

我正在使用此代码:

1
2
3
4
5
6
7
$('body').click(function() {
   $('.form_wrapper').hide();
});

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

这个HTML:

1
2
   I Agree
   Disagree

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


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

1
2
3
4
5
6
7
8
9
10
$(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
2
3
4
5
6
7
8
9
10
11
12
13
14
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元素也不是其子代元素时,才隐藏#CONTAINER元素。

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


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

类似:

1
2
3
4
5
6
7
8
9
10
$("body").click
(
  function(e)
  {
    if(e.target.className !=="form_wrapper")
    {
      $(".form_wrapper").hide();
    }
  }
);

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


现场演示

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

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

更新:

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

现场演示

1
2
3
4
5
6
7
8
9
10
11
12
$(".button").click(function(e){
    $(".dropdown").show();
     e.stopPropagation();
});

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

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


1
2
3
4
5
$(document).click(function(event) {
    if ( !$(event.target).hasClass('form_wrapper')) {
         $(".form_wrapper").hide();
    }
});


将解决方案更新为:

  • 使用mouseenter和mouseleave代替
  • 使用活动事件绑定

var mouseOverActiveElement = false;

1
2
3
4
5
6
7
8
9
10
$('.active').live('mouseenter', function(){
    mouseOverActiveElement = true;
}).live('mouseleave', function(){
    mouseOverActiveElement = false;
});
$("html").click(function(){
    if (!mouseOverActiveElement) {
        console.log('clicked outside active element');
    }
});


对于最流行的答案,没有jquery的解决方案:

1
2
3
4
5
6
7
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


esc功能的现场演示

可在台式机和移动设备上使用

1
2
3
4
5
6
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 ensure that your element is really visible when you do clicks on the document:if($pop.is(':visible') && (notH||e.which==27)) $pop.hide();


这样的东西不管用吗?

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

});

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

});


您可以将tabindex设置为父级,并监听focusout事件,而不必每次单击dom来隐藏一个特定元素。

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

所以您的HTML应该是:

1
2
    I Agree
    Disagree

你的JS:

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

这是我在另一个线程上找到的一个jsfidle,也可以使用esc键:http://jsfidle.net/s5ftb/404

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
    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()
      }
    })


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

1
2
3
4
5
6
7
8
9
$(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();
    }
});

甚至是雪橇:

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


基于prc322的完美答案。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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
  • 我希望这能帮助别人!


    如果您的iOS有问题,则mouseup无法在Apple设备上工作。

    jquery中的mousedown/mouseup是否适用于iPad?

    我用这个:

    1
    2
    3
    4
    5
    6
    7
    8
    $(document).bind('touchend', function(e) {
            var container = $("YOURCONTAINER");

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

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    var n = 0;
    $("#container").mouseenter(function() {
    n = 0;

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

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

    如果单击,则返回false。表单包装:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    $('body').click(function() {
      $('.form_wrapper').click(function(){
      return false
    });
       $('.form_wrapper').hide();
    });

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

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

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

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


    1
    2
    3
    4
    5
    6
    7
    $(document).ready(function() {
        $('.modal-container').on('click', function(e) {
          if(e.target == $(this)[0]) {
            $(this).removeClass('active'); // or hide()
          }
        });
    });
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    .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;
    }
    1
    2
    3
    4
    5
    6
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">

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


    1
    2
    3
    4
    5
    6
     $('body').click(function(event) {
        if (!$(event.target).is('p'))
        {
            $("#e2ma-menu").hide();
        }
    });

    p是元素名。也可以传递ID、类或元素名。


    (只是在prc322的答案上加了一句。)

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

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    $(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();
        }
    });

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


    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    <!DOCTYPE html>
    <html>
    <head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js">


    $(document).ready(function(){
      $("#hide").click(function(){
        $("p").hide();
      });
      $("#show").click(function(){
        $("p").show();
      });
    });

    </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>

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

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

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    $(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");
            }
        })
    })


    1
    2
    3
    4
    5
    6
    7
    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);
        }
    });

    这么多的答案,一定是一个有权利的通行证加了一个…我没有看到当前(jquery 3.1.1)的答案-所以:

    1
    2
    3
    4
    5
    $(function() {
        $('body').on('mouseup', function() {
            $('#your-selector').hide();
        });
    });

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

    1
    2
    3
    4
    5
    6
    7
    8
    9
    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';
        }
       }
    })

    我是这样做的:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    var close = true;

    $(function () {

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

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


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

    });

    1
    2
    3
    4
    5
    6
    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");  

    });

    小提琴


    常规和触摸设备的切换

    不久前,我在这里读了一些答案,并创建了一些用于DIV的代码,它的函数是弹出气泡。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    $('#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);
                }
            });
        }
    });

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

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    $('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);
                }
            });
        }
    });

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

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
        $('.form_wrapper').show(function(){

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

        });

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

    10


    根据文件,.blur()的工作时间超过了的标签。例如:

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


    1
    2
    3
    4
    5
    6
    7
    8
    $(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");

    })});


    我认为这会容易得多。我是这样做的:

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