【问题标题】:Close popup by Esc if there are many of them on the page如果页面上有很多弹出窗口,请按 Esc 关闭弹出窗口
【发布时间】:2021-12-07 21:57:39
【问题描述】:

我一直在网上搜索,但找不到问题的答案,这似乎有一个简单的解决方案。

我的页面上有三个弹出窗口,用户可以打开它们,打开和关闭它们的功能看起来很常见:

const popupPicture = document.querySelector(".popup_pic");
const popupProfile = document.querySelector(".popup_profile");
const popupImage = document.querySelector(".popup_image");

function openPopup(popup) {
  popup.classList.add("popup_opened");
}

function closePopup(popup) {
  popup.classList.remove("popup_opened");
}

然后我将其中一个弹出变量传递给 closePopup 或 openPopup 作为变量。 比如

closePopupButton.addEventListener("click", () => closePopup(popupProfile));
closePopupImageButton.addEventListener("click", () => closePopup(popupImage));
closePopupPictureButton.addEventListener("click", () => closePopup(popupPicture));

打开弹出窗口也是如此。我现在需要通过 Escape 按钮关闭功能。我知道如果只有一个弹出以下代码很容易实现:

document.addEventListener("keydown", function (evt) {
  if (evt.key === "Escape") {
    // and close popup here
  }
});

但是在我的情况下有三个弹出窗口,我不知道,我应该关闭它们。我当然可以通过这种丑陋的方式来做到这一点:

document.addEventListener("keydown", function (evt) {
  if (evt.key === "Escape") {
    closePopup(popupProfile);
    closePopup(popupImage);
    closePopup(popupPicture);
  }
});

它解决了我的情况,但我想知道是否有更优雅的解决方案,它不需要调用两个不应该调用的函数。

希望我能清楚地说明我的问题。

非常感谢您!

【问题讨论】:

    标签: javascript popup


    【解决方案1】:

    只需使用document.getElementsByClassName()

    这将返回包含给定类字符串的元素的HTMLCollection,然后您只需要遍历它。

    这是一个例子:https://jsfiddle.net/whp8xzb2/1/

    示例中使用的元素具有分配给它们的多个类,类似于您的代码。它使用 document.getElementsByClassName("foo") 检索这些元素,然后使用 for 循环遍历结果:

    for (let item of results) {
        console.log(item)
    }
    

    【讨论】:

      猜你喜欢
      • 2014-08-30
      • 2011-06-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多