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

发布于 2024-07-16 11:43:20 字数 192 浏览 8 评论 0原文

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

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

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

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(21

荒人说梦 2024-07-23 11:43:20

如果我理解,当您单击除 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,它将取消点击事件。

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:

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

溺ぐ爱和你が 2024-07-23 11:43:20

试试这个,

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

  });
});

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

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

  });
});
秋风の叶未落 2024-07-23 11:43:20

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

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').one 自动执行此行为(请参阅:文档)但因为我们需要在处理程序中执行条件,所以这里不适用。

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.

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.

森林迷了鹿 2024-07-23 11:43:20

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

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

<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>
一梦等七年七年为一梦 2024-07-23 11:43:20

谢谢,托马斯。 我是 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>

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

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.

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>
那一片橙海, 2024-07-23 11:43:20

您还可以做的是:

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

  var container = $("div");

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

   }

});

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

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.

心房敞 2024-07-23 11:43:20

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

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

如果我可以在这方面帮助别人,请告诉我。

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.

猫性小仙女 2024-07-23 11:43:20
  $(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 元素。
在做每件事之前,请先理解代码并复制它......

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

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

汹涌人海 2024-07-23 11:43:20

尝试这个:

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

Try this:

 $(document).mouseup(function (e) {
    var div = $("#yourdivid");
    if (!div.is(e.target) && div.has(e.target).length === 0) 
    {
       div.hide();
     }
    });
独自唱情﹋歌 2024-07-23 11:43:20

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

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

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

$(document).on('click', function(e) {
    if(!$.contains($('.yourContainer').get(0), e.target)) {
        $('.yourContainer').hide();
    }
});
只是一片海 2024-07-23 11:43:20

试试这个,它对我来说非常有效。

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

Try this, it's working perfect for me.

$(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();
    }
});
场罚期间 2024-07-23 11:43:20
$('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/

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

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

but you need to keep in mind these things as well. http://css-tricks.com/dangers-stopping-event-propagation/

五里雾 2024-07-23 11:43:20

这是一个基于 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/

Here is a working CSS/small JS solution based on the answer of Sandeep Pal:

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

Try it out by clicking the checkbox and then outside of the menu:

https://jsfiddle.net/qo90txr8/

人生戏 2024-07-23 11:43:20

这不起作用 - 当您单击 .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>

This doesn't work - it hides the .myDIV when you click inside of it.

$('.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>
你不是我要的菜∠ 2024-07-23 11:43:20

对上述建议只有 2 个小改进:

  • 完成后取消绑定 document.click
  • 停止触发此事件的传播,假设它是一次点击

    jQuery(thelink).click(function(e){ 
          jQuery(thepop).show(); 
    
          // 绑定隐藏控件 
          var jpop=jQuery(thepop); 
          jQuery(document).bind("click.hidethepop", function() { 
                  jpop.隐藏(); 
                  // 解除隐藏控件的绑定 
                  jQuery(document).unbind("click.hidethepop"); 
          }); 
          // 单击 pop 时不要关闭 pop 
          jQuery(thepop).click(函数(e) { 
              e.stopPropagation(); 
          }); 
          // 现在不要关闭 pop  
          e.stopPropagation(); 
      }); 
      

Just 2 small improvements to the above suggestions:

  • unbind the document.click when done
  • stop propagation on the event that triggered this, assuming its a 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();
    });
    
萤火眠眠 2024-07-23 11:43:20
$(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>

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

提笔书几行 2024-07-23 11:43:20
$( "element" ).focusout(function() {
    //your code on element
})
$( "element" ).focusout(function() {
    //your code on element
})
执手闯天涯 2024-07-23 11:43:20

这是由上面的其他解决方案得出的。

$(document).ready(function(){  

    $("button").click(function(event){
        $(".area").toggle();
        event.stopPropagation();    //stops the click event to go "throu" the button an hit the document
    });
    
    
    $(document).click(function() {
        $(".area").hide();
    });
    
    
    $(".interface").click(function(event) {
        event.stopPropagation();
        return false;                                        
    });
});

<div>
    <div>
        <button> Press here for content</button> 
      <div class="area">
        <div class="interface"> Content</div>
      </div>
    </div>       
</div>

This is made from the other solutions above.

$(document).ready(function(){  

    $("button").click(function(event){
        $(".area").toggle();
        event.stopPropagation();    //stops the click event to go "throu" the button an hit the document
    });
    
    
    $(document).click(function() {
        $(".area").hide();
    });
    
    
    $(".interface").click(function(event) {
        event.stopPropagation();
        return false;                                        
    });
});

<div>
    <div>
        <button> Press here for content</button> 
      <div class="area">
        <div class="interface"> Content</div>
      </div>
    </div>       
</div>
雪花飘飘的天空 2024-07-23 11:43:20
$(document).click(function() {
  var container = $("#container");
  if (!container.is(event.target) &&
    !container.has(event.target).length) {
    container.hide();
  }
});


$(document).click(function() {
  var container = $("#container");
  if (!container.is(event.target) &&
    !container.has(event.target).length) {
    container.hide();
  }
});


瀟灑尐姊 2024-07-23 11:43:20
$(document).mouseup(function (e)
{
    var mydiv = $('div#mydiv');
    if (!mydiv.is(e.target) && mydiv.has(e.target).length === 0){
       search.slideUp();
    }
});
$(document).mouseup(function (e)
{
    var mydiv = $('div#mydiv');
    if (!mydiv.is(e.target) && mydiv.has(e.target).length === 0){
       search.slideUp();
    }
});
千年*琉璃梦 2024-07-23 11:43:20

简单的解决方案:在某个特定元素之外的任何位置隐藏单击事件上的元素。

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

Simple Solution: hide an element on a click event anywhere outside of some specific element.

$(document).on('click', function () {
                $('.element').hide();
            });
            //element will not Hide on click some specific control inside document
            $('.control-1').on('click', function (e) {
                e.stopPropagation();
            });
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文