📜  当用户使用 jQuery 在 div 之外单击时如何隐藏 div?

📅  最后修改于: 2021-11-24 05:16:51             🧑  作者: Mango

如果使用两种方法在元素外部单击鼠标,则可以隐藏或显示元素。

方法一:使用最接近的方法:

  1. mouseup 事件是首先检查文档
    $(document).mouseup(function (e) {
        // rest code here
    }
    
  2. 在目标点击时调用最接近的() 方法。此方法返回 DOM 树中所选元素的第一个祖先。然后在结果上使用 length 属性来找出祖先的数量。如果没有祖先,则意味着点击在元素之外。
    if ($(e.target).closest(".container").length === 0) {
        // rest code here
    }
    
  3. 使用 hide() 方法隐藏元素。
    $(".container").hide();
    

    例子:

    
    
      
    
        
            How to hide a div when the user 
            clicks outside of it using jQuery?
        
          
        
          
        
    
      
    
        

            GeeksForGeeks     

                        How to hide a div when the user clicks         outside of it using jQuery?                 

    Click outside the green div to hide it

               
                                       

    输出:

    • 在 div 内单击:
      点击内部
    • 在 div 外单击:
      点击外面

    方法二:检查元素是否包含点击目标:

    1. mouseup 事件是首先检查文档
      $(document).mouseup(function (e) {
          // rest code here
      }
      
    2. 元素被检查两件事,即通过将 is() 方法和 has() 方法传递给点击目标,点击不会落在元素上。

      is() 方法根据指定元素检查当前元素。点击目标作为参数传递,整个结果被否定以基本上检查点击是否在元素之外。

      has() 方法用于返回与传递给此方法的至少一个元素匹配的所有元素。然后在结果上使用 length 属性来检查是否返回了任何元素。如果没有返回元素,则表示点击在元素之外。

      if(!container.is(e.target) && container.has(e.target).length === 0) {
          // rest code here
      }
      
    3. 使用 hide() 方法隐藏元素。
      $(".container").hide();
      

      例子:

      
      
            
      
          
              How to hide a div when the user clicks
              outside of it using jQuery?
          
            
          
            
          
      
        
      
          

              GeeksForGeeks     

                          How to hide a div when the user clicks         outside of it using jQuery?                 

      Click outside the green div to hide it

                 
                    

      输出:

      • 在 div 内单击:
        点击内部
      • 在 div 外单击:
        点击外面

      jQuery 是一个开源 JavaScript 库,它简化了 HTML/CSS 文档之间的交互,它以其“少写,多做”的理念而广为人知。
      您可以按照此 jQuery 教程和 jQuery 示例从头开始学习 jQuery。