You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现点击图片以外任意区域关闭Lightbox图片弹窗?

实现点击图片以外区域关闭弹窗的方法

你可以通过给弹窗容器(.lightbox)添加点击事件监听,判断点击目标是否为弹窗背景区域(即图片以外的部分)来实现这个功能,具体修改如下:

  1. 添加点击外部区域关闭的处理函数:
const closeLightboxOnOutsideClick = (event) => {
  // 当点击的目标就是lightbox本身(背景区域)时关闭弹窗
  if (event.target === lightbox) {
    closeLightbox();
  }
};
  1. 在showLightbox函数中添加这个事件监听(弹窗显示时才监听,避免无效触发):
const showLightbox = (imgSrc) => {
  lightbox.querySelector("img").src = imgSrc;
  lightbox.classList.add("show");
  document.body.style.overflow = "hidden";

  document.addEventListener("keydown", closeLightboxOnEsc);
  // 添加外部点击监听
  document.addEventListener("click", closeLightboxOnOutsideClick);
};
  1. 在closeLightbox函数中移除这个事件监听,防止内存泄漏:
const closeLightbox = () => {
  lightbox.classList.remove("show");
  document.body.style.overflow = "auto";

  document.removeEventListener("keydown", closeLightboxOnEsc);
  // 移除外部点击监听
  document.removeEventListener("click", closeLightboxOnOutsideClick);
};

完整修改后的代码:

const allImages = document.querySelectorAll(".images .img");
const lightbox = document.querySelector(".lightbox");
const closeImgBtn = lightbox.querySelector(".close-icon");

allImages.forEach((img) => {
  img.addEventListener("click", () =>
    showLightbox(img.querySelector("img").src)
  );
});

const showLightbox = (imgSrc) => {
  lightbox.querySelector("img").src = imgSrc;
  lightbox.classList.add("show");
  document.body.style.overflow = "hidden";

  document.addEventListener("keydown", closeLightboxOnEsc);
  document.addEventListener("click", closeLightboxOnOutsideClick);
};

const closeLightbox = () => {
  lightbox.classList.remove("show");
  document.body.style.overflow = "auto";

  document.removeEventListener("keydown", closeLightboxOnEsc);
  document.removeEventListener("click", closeLightboxOnOutsideClick);
};

const closeLightboxOnEsc = (event) => {
  if (event.key === "Escape") {
    closeLightbox();
  }
};

const closeLightboxOnOutsideClick = (event) => {
  if (event.target === lightbox) {
    closeLightbox();
  }
};

closeImgBtn.addEventListener("click", closeLightbox);

原理说明:

  • 当弹窗显示时,给document添加点击事件监听,每次点击都会检查目标元素是否是.lightbox本身(也就是弹窗的背景层,而非里面的图片或关闭按钮)。
  • 如果点击的是背景层,就触发closeLightbox函数关闭弹窗。
  • 弹窗关闭时移除监听,避免后续点击页面时误触发关闭逻辑,同时减少不必要的事件监听开销。

内容的提问来源于stack exchange,提问作者Ilkin Safterov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 20:13:09