【问题标题】:How to close a popup on a click outside of it如何在弹出窗口外单击关闭弹出窗口
【发布时间】:2023-02-09 17:47:54
【问题描述】:

我的标题中有一个弹出按钮。我需要确保在其区域外单击时弹出窗口关闭。我怎样才能做到这一点?在代码中,我试图在单击 body.active-search 时添加删除活动类,但它不起作用。

const searchButton = document.querySelector(".search-button");
const searchPopup = document.querySelector(".search-popup");

if (searchButton) {
  searchButton.addEventListener("click", () => {
    searchPopup.classList.toggle("active");
    searchButton.classList.toggle("active");
    body.classList.toggle("active-search");
  });
}

$(".active-search").click(function() {
  searchPopup.remove("active");
  searchButton.remove("active");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<header>
  <div class="search-wrapper">
    <button class="search-button">Open Search</button>
    <div class="search-popup"></div>
  </div>
</header>

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    您可以向文档添加一个事件侦听器,并检查点击目标是否在searchPopup 元素之外。如果目标在外面,你可以从searchPopupsearchButton中删除活动类。

    const searchButton = document.querySelector(".search-button");
    const searchPopup = document.querySelector(".search-popup");
    
    if (searchButton) {
      searchButton.addEventListener("click", () => {
        searchPopup.classList.toggle("active");
        searchButton.classList.toggle("active");
        body.classList.toggle("active-search");
      });
      
      document.addEventListener("click", function(event) {
        if (!searchPopup.contains(event.target) && searchPopup.classList.contains("active")) {
          searchPopup.classList.remove("active");
          searchButton.classList.remove("active");
          body.classList.remove("active-search");
        }
      });
    }
    

    请注意,body 需要在您的代码中定义。

    【讨论】:

      猜你喜欢
      • 2012-12-21
      • 1970-01-01
      • 1970-01-01
      • 2022-12-31
      • 1970-01-01
      • 2018-08-20
      • 1970-01-01
      • 2021-11-21
      • 1970-01-01
      相关资源
      最近更新 更多