簡體   English   中英

jQuery切換菜單,在外部單擊時隱藏下拉菜單內容

[英]jQuery toggle menu, hide dropdown contents when outside click

我已經使用jQuery創建了一個切換菜單,效果很好,但是當在其外部單擊時如何隱藏下拉菜單內容。請幫助我。 謝謝,我正在制作一個產品評論和用戶提交的帖子的網站。 我需要一些幫助才能成功。

  <script> $(".dropbtn").click(function(e){ $(".dropdown-content").toggle(); e.preventDefault(); }); $(".dropbtn").click(function(e){ $(this).hide(); e.preventDefault(); }); $(".dropbtn").click(function(e){ $(".dropbtnhide").show(); e.preventDefault(); }); $(".dropbtnhide").click(function(e){ $(".dropdown-content").hide(); e.preventDefault(); }); $(".dropbtnhide").click(function(e){ $(this).hide(); e.preventDefault(); }); $(".dropbtnhide").click(function(e){ $(".dropbtn").show(); e.preventDefault(); }); $(".dropdown-content").click(function(e){ e.preventDefault(); }); </script> 

 .dropbtnhide{display:none; position:relative;} .dropbtn{display:inline-block; position:relative;} <!-- begin snippet: js hide: false console: true babel: false --> 
  <div class="celldisplay dropdown"> <button class="dropbtnhide "><i class="far fa-ellipsis-h"></i></button> <button class="dropbtn"> <i class="far fa-ellipsis-v"></i></button> <li><a></a> </li> </div> 

您可以通過為windowclick事件( Element.contains(event.target) )添加事件偵聽器來檢查Element包含事件的目標。

演示:

 .dropbtn { background-color: #4CAF50; color: white; padding: 16px; font-size: 16px; border: none; cursor: pointer; } .dropdown { position: relative; display: inline-block; } .dropdown-content { display: none; position: absolute; background-color: #f9f9f9; min-width: 160px; box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2); z-index: 1; } .dropdown-content a { color: black; padding: 12px 16px; text-decoration: none; display: block; } 
 <div class="dropdown" id="dropdown"> <button class="dropbtn">Dropdown</button> <div class="dropdown-content" id="dropdown-content"> <a href="#">Link 1</a> <a href="#">Link 2</a> <a href="#">Link 3</a> </div> </div> <script> var dropdown = document.getElementById("dropdown"); var open = false; dropdown.onclick = function(){ if(!open){ document.getElementById("dropdown-content").style.display = "block"; open = true; } else { document.getElementById("dropdown-content").style.display = "none"; open = false; } } window.addEventListener("click", function(event){ if(!dropdown.contains(event.target)){ document.getElementById("dropdown-content").style.display = "none"; open = false; console.log("Click outside of dropdown"); } }); </script> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM