jQuery 如何在元素之外的任何位置隐藏单击事件上的元素?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/714471/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 09:37:12  来源:igfitidea点击:

How do I hide an element on a click event anywhere outside of the element?

jqueryeventsevent-bubbling

提问by Franek

I would like to know whether this is the correct way of hiding visible elements when clicked anywhere on the page.

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

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

The element (div, span, etc.) shouldn't disappear when a click event occurs within the boundaries of the element.

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

回答by Jeremy B.

If I understand, you want to hide a div when you click anywhere but the div, and if you do click while over the div, then it should NOT close. You can do that with this code:

如果我理解,当你点击除 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
});

This binds the click to the entire page, but if you click on the div in question, it will cancel the click event.

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

回答by TStamper

Try this

尝试这个

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

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

  });
});

I use class name instead of ID, because in asp.net you have to worry about the extra stuff .net attaches to the id

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

EDIT-Since you added a another piece, it would work like this:

编辑 -由于您添加了另一块,它会像这样工作:

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

  });
});

回答by Ben Taylor

As of jQuery 1.7 there's a new way to handle events. I thought I'd answer here just to demonstrate how I might go about doing this the "new" way. If you haven't, I recommend you read the jQuery docs for the "on" method.

从 jQuery 1.7 开始,有一种处理事件的新方法。我想我会在这里回答只是为了展示我如何以“新”的方式去做这件事。如果您还没有,我建议您阅读jQuery 文档以了解“on”方法

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

Here we're abusing jQuery's selectors and bubbling of events. Note that I make sure I clean the event handler up afterwards. You can automate this behaviour with $('.container').one(see: docs) but because we need to do conditionals within the handler that isn't applicable here.

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

回答by Ben Taylor

This following code example seems to work best for me. While you can use 'return false' that stops all handling of that event for the div or any of it's children. If you want to have controls on the pop-up div (a pop-up login form for example) you need to use event.stopPropogation().

以下代码示例似乎最适合我。虽然您可以使用 '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>

回答by Tommy

Thanks, Thomas. I'm new to JS and I've been looking crazy for a solution to my problem. Yours helped.

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

I've used jquery to make a Login-box that slides down. For best user experience I desided to make the box disappear when user clicks somewhere but the box. I'm a little bit embarrassed over using about four hours fixing this. But hey, I'm new to JS.

我使用 jquery 制作了一个向下滑动的登录框。为了获得最佳的用户体验,我希望在用户点击框以外的某处时让框消失。我对用大约四个小时来解决这个问题感到有点尴尬。但是,嘿,我是 JS 新手。

Maybe my code can help someone out:

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

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

回答by Sandeep Pal

What you can also do is:

您还可以做的是:

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

  var container = $("div");

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

   }

});

If your target is not a div then hide the div by checking its length is equal to zero.

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

回答by foxybagga

I did the below. Thought of sharing so someone else could also benefit.

我做了下面的。想到分享,这样其他人也可以受益。

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

Let me know if I can help someone on this.

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

回答by Nalan Madheswaran

Try this:

尝试这个:

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

回答by Renato Gama

Another way of hiding the container div when a click happens in a not children element;

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

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

回答by Shaikh Arbaaz

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

Here #suggest_input in is the name of textbox and .suggest_container is the ul class name and .suggest_div is the main div element for my auto-suggest.

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

this code is for hiding the div elements by clicking any where in the screen. Before doing every thing please understand the code and copy it...

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