【问题标题】:How do I hide an element on a click event anywhere outside of the element?如何在元素外部的任何位置隐藏单击事件上的元素?
【发布时间】:2010-10-17 09:36:50
【问题描述】:

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

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

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

【问题讨论】:

    标签: jquery events event-bubbling


    【解决方案1】:

    如果我理解,您希望在单击 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,它会取消点击事件。

    【讨论】:

    • 这工作正常.. 但是当我点击调用弹出窗口的按钮时,弹出窗口来了,然后又立即消失了。当文档一次执行两个操作时,该怎么做。在 bodyClick 上调用弹出窗口并在 bodyClick 上淡出弹出窗口
    • @VeerShrivastav 同样发生在这里。 e.stopPropagation();将停止所有点击处理程序
    • 如果.myDiv 元素中有其他元素,这将在 Safari 中不起作用。例如,如果您在 .myDiv 中有一个选择下拉菜单。当您单击选择时,它会认为您在框外单击。
    【解决方案2】:

    试试这个

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

    【讨论】:

      【解决方案3】:

      从 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').one (see: docs) 自动执行此行为,但因为我们需要在处理程序中执行不适用于此处的条件。

      【讨论】:

        【解决方案4】:

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

        【讨论】:

          【解决方案5】:

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

          【讨论】:

            【解决方案6】:

            你还可以做的是:

            $(document).click(function (e)
            {
            
              var container = $("div");
            
               if (!container.is(e.target) && container.has(e.target).length === 0)
              {
             container.fadeOut('slow');
            
               }
            
            });
            

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

            【讨论】:

              【解决方案7】:

              我做了以下。考虑分享以便其他人也可以受益。

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

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

              【讨论】:

              • 很棒的代码,如果没有点击 div#newButtonDiv 则不会执行。我建议您删除第 4 行的第二个 .click()(如果您这样做,请记住删除右大括号、括号和分号 - 第 9 行)。
              【解决方案8】:

              试试这个:

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

              【讨论】:

                【解决方案9】:

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

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

                【讨论】:

                  【解决方案10】:
                    $(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 in 是文本框的名称,.suggest_container 是 ul 类名,.suggest_div 是我的自动建议的主要 div 元素。

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

                  【讨论】:

                    【解决方案11】:

                    试试这个,它非常适合我。

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

                    【讨论】:

                      【解决方案12】:
                      $('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/

                      【讨论】:

                        【解决方案13】:

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

                        【讨论】:

                          【解决方案14】:

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

                          【讨论】:

                          • 所以你希望 div 在放置链接时显示,然后将 e.stopPropa.. 从那里取出并按照我的选择
                          【解决方案15】:

                          对上述建议仅做 2 处小改进:

                          • 解绑文档。完成后点击
                          • 停止传播触发此事件的事件,假设它是一次点击

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

                          【讨论】:

                            【解决方案16】:

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

                            【讨论】:

                              【解决方案17】:
                              $( "element" ).focusout(function() {
                                  //your code on element
                              })
                              

                              【讨论】:

                              【解决方案18】:

                              这是由上述其他解决方案制成的。

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

                              【讨论】:

                                【解决方案19】:
                                $(document).click(function() {
                                  var container = $("#container");
                                  if (!container.is(event.target) &&
                                    !container.has(event.target).length) {
                                    container.hide();
                                  }
                                });
                                
                                
                                

                                【讨论】:

                                  【解决方案20】:
                                  $(document).mouseup(function (e)
                                  {
                                      var mydiv = $('div#mydiv');
                                      if (!mydiv.is(e.target) && mydiv.has(e.target).length === 0){
                                         search.slideUp();
                                      }
                                  });
                                  

                                  【讨论】:

                                    【解决方案21】:

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

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

                                    【讨论】:

                                      猜你喜欢
                                      • 1970-01-01
                                      • 2012-09-25
                                      • 2012-12-03
                                      • 1970-01-01
                                      • 2020-11-20
                                      • 1970-01-01
                                      • 1970-01-01
                                      • 2018-12-24
                                      • 2017-12-10
                                      相关资源
                                      最近更新 更多