单击页面上任何位置的jQuery隐藏元素,但不在特定控件上

问题描述 投票:112回答:18

我想知道这是否是在页面上任何位置单击时隐藏可见元素的正确方法。

$(document).click(function (event) {            
    $('#myDIV:visible').hide();
});

当元素边界内发生click事件时,元素(div,span等)不应消失。

jquery events event-bubbling
18个回答
198
投票

如果我理解你想要隐藏一个div当你点击除div之外的任何地方,如果你点击div而不是它,那么它不应该关闭。你可以这样做:

$(document).click(function() {
    alert("me");
});
$(".myDiv").click(function(e) {
    e.stopPropagation(); // This is the preferred method.
    return false;        // This should not be used unless you do not want
                         // any click events registering inside the div
});

这会将点击绑定到整个页面,但如果您单击有问题的div,它将取消单击事件。


3
投票

试试这个:

 $(document).mouseup(function (e) {
    var div = $("#yourdivid");
    if (!div.is(e.target) && div.has(e.target).length === 0) 
    {
       div.hide();
     }
    });

2
投票

试试这个,它对我来说很完美。

$(document).mouseup(function (e)
{
    var searchcontainer = $("#search_container");

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

2
投票
$('html').click(function() {
//Hide the menus if it is visible
});

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

但你需要记住这些事情。 http://css-tricks.com/dangers-stopping-event-propagation/


2
投票

这是一个基于Sandeep Pal答案的工作CSS /小型JS解决方案:

$(document).click(function (e)
{
  if (!$("#noticeMenu").is(e.target) && $("#noticeMenu").has(e.target).length == 0)
  {
   $("#menu-toggle3").prop('checked', false);
  }
});

单击复选框然后单击菜单外部尝试:

https://jsfiddle.net/qo90txr8/


1
投票

这不起作用 - 当你点击它时,它会隐藏.myDIV。

$('.openDiv').click(function(e) {
$('.myDiv').show(); 
e.stopPropagation();
})

$(document).click(function(){  
$('.myDiv').hide(); 

});

});

<a class="openDiv">DISPLAY DIV</a>

<div class="myDiv">HIDE DIV</div>

1
投票

对上述建议只做了两点小改进:

  • 完成后取消绑定document.click
  • 假设点击一下,在触发此事件的事件上停止传播 jQuery(thelink).click(function(e){ jQuery(thepop).show(); // bind the hide controls var jpop=jQuery(thepop); jQuery(document).bind("click.hidethepop", function() { jpop.hide(); // unbind the hide controls jQuery(document).unbind("click.hidethepop"); }); // dont close thepop when you click on thepop jQuery(thepop).click(function(e) { e.stopPropagation(); }); // and dont close thepop now e.stopPropagation(); });

1
投票

$(document).ready(function(){

$("button").click(function(){
   
       
        $(".div3").toggle(1000);
    });
   $("body").click(function(event) {
   if($(event.target).attr('class') != '1' && $(event.target).attr('class') != 'div3'){
       $(".div3").hide(1000);}
    }); 
   
    
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script>
<button class="1">Click to fade in boxes</button><br><br>

<body style="width:100%;height:200px;background-color:pink;">
<div class="div3" style="width:80px;height:80px;display:none;background-color:blue;"></div><body>

0
投票
$(document).mouseup(function (e)
{
    var mydiv = $('div#mydiv');
    if (!mydiv.is(e.target) && mydiv.has(e.target).length === 0){
       search.slideUp();
    }
});

0
投票
$( "element" ).focusout(function() {
    //your code on element
})

0
投票

隐藏点击文档上的元素

$(document).on('click', function () {
                $('.element').hide();
            });
            //element will not Hide on click some specific control inside document
            $('.control-1, .control-2').on('click', function (e) {
                e.stopPropagation();
            });

23
投票

试试这个

 $('.myDiv').click(function(e) { //button click class name is myDiv
  e.stopPropagation();
 })

 $(function(){
  $(document).click(function(){  
  $('.myDiv').hide(); //hide the button

  });
});

我使用类名而不是ID,因为在asp.net中你必须担心额外的东西.net附加到id

编辑 - 既然你添加了另一篇文章,它会像这样工作:

 $('.myDiv').click(function() { //button click class name is myDiv
  e.stopPropagation();
 })

 $(function(){
  $('.openDiv').click(function() {
  $('.myDiv').show(); 

  });
  $(document).click(function(){  
  $('.myDiv').hide(); //hide the button

  });
});

22
投票

从jQuery 1.7开始,有一种处理事件的新方法。我以为我会在这里回答只是为了演示如何以“新”的方式来做这件事。如果你还没有,我建议你阅读jQuery docs for the "on" method

var handler = function(event){
  // if the target is a descendent of container do nothing
  if($(event.target).is(".container, .container *")) return;

  // remove event handler from document
  $(document).off("click", handler);

  // dostuff
}

$(document).on("click", handler);

在这里,我们滥用jQuery的选择器和冒泡事件。请注意,我确保事后清理事件处理程序。您可以使用$('.container').onesee: docs)自动执行此行为,但因为我们需要在处理程序中执行不适用的条件。


13
投票

以下代码示例似乎最适合我。虽然你可以使用'return false'来停止对div或其中任何一个孩子的所有事件处理。如果要对弹出div(例如弹出式登录表单)进行控制,则需要使用event.stopPropogation()。

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
</head>
<body>
    <a id="link" href="#">show box</a>
    <div id="box" style="background: #eee; display: none">
        <p>a paragraph of text</p>
        <input type="file"  />
    </div>

    <script src="jquery.js" type="text/javascript"></script>

    <script type="text/javascript">
        var box = $('#box');
        var link = $('#link');

        link.click(function() {
            box.show(); return false;
        });

        $(document).click(function() {
            box.hide();
        });

        box.click(function(e) {
            e.stopPropagation();
        });

    </script>
</body>
</html>

6
投票

谢谢,托马斯。我是JS的新手,我一直在寻找解决问题的方法。你的帮助。

我使用jquery制作一个向下滑动的登录框。为了获得最佳用户体验,我希望当用户点击某个地方而不是框时,该框会消失。使用大约四个小时解决这个问题我有点尴尬。但是,嘿,我是JS的新手。

也许我的代码可以帮助某人:

<body>
<button class="login">Logg inn</button>
<script type="text/javascript">

    $("button.login").click(function () {
        if ($("div#box:first").is(":hidden")) {
                $("div#box").slideDown("slow");} 
            else {
                $("div#box").slideUp("slow");
                }
    });
    </script>
<div id="box">Lots of login content</div>

<script type="text/javascript">
    var box = $('#box');
    var login = $('.login');

    login.click(function() {
        box.show(); return false;
    });

    $(document).click(function() {
        box.hide();
    });

    box.click(function(e) {
        e.stopPropagation();
    });

</script>

</body>

5
投票

你还可以做的是:

$(document).click(function (e)
{

  var container = $("div");

   if (!container.is(e.target) && container.has(e.target).length === 0)
  {
 container.fadeOut('slow');

   }

});

如果您的目标不是div,则通过检查其长度等于零来隐藏div。


5
投票

我做了以下。分享的想法让其他人也受益。

$("div#newButtonDiv").click(function(){
    $(this).find("ul.sub-menu").css({"display":"block"});

    $(this).click(function(event){
        event.stopPropagation();
        $("html").click(function(){
            $(this).find("ul.sub-menu").css({"display":"none"});
        }
    });
});

如果我可以帮助此人,请告诉我。


3
投票

在非子元素中发生单击时隐藏容器div的另一种方法;

$(document).on('click', function(e) {
    if(!$.contains($('.yourContainer').get(0), e.target)) {
        $('.yourContainer').hide();
    }
});

3
投票
  $(document).on('click', function(e) { // Hides the div by clicking any where in the screen
        if ( $(e.target).closest('#suggest_input').length ) {
            $(".suggest_div").show();
        }else if ( ! $(e.target).closest('.suggest_container').length ) {
            $('.suggest_div').hide();
        }
    });

这里#suggest_input输入是文本框的名称,而.suggest_container是ul类名,而.suggest_div是我自动建议的主要div元素。

此代码用于通过单击屏幕中的任何位置来隐藏div元素。在做每件事之前,请理解代码并复制它......

© www.soinside.com 2019 - 2024. All rights reserved.