首页 > 解决方案 > 如何将关闭按钮添加到我的灯箱?所以我可以从按钮关闭图片,而不是单击灯箱中的任何位置

问题描述

我正在使用这个简单的灯箱,但我想通过在右上角添加一个关闭按钮来使其更高级。

因此,当它在灯箱中显示图像时,我可以使用关闭按钮将其关闭,而不是单击灯箱中的任何位置来关闭图片。

const lightbox = document.createElement('div')
lightbox.id = 'lightbox'
document.body.appendChild(lightbox)

const images = document.querySelectorAll('.columnimg')
images.forEach(columnimg => {
  columnimg.addEventListener('click', e => {
    lightbox.classList.add('active')
    const img = document.createElement('img')
    img.src = columnimg.src

    while (lightbox.firstChild) {
      lightbox.removeChild(lightbox.firstChild)
    }
    lightbox.appendChild(img)
  })
})

lightbox.addEventListener('click', e => {
  if (e.target !== e.currentTarget) return
  lightbox.classList.remove('active')
})
<style><!--

  #lightbox {
    position: fixed;
    z-index: 1000;
    top: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, .8);
    display: none;
  }

  #lightbox.active {
    display: flex;
    justify-content: center;
    align-items: center;
  }

  #lightboximg {
    max-width: 90%;
    max-height: 80%;
    padding: 4px;
    background-color: black;
    border: 2px solid white;
    }
.rowimg{

}
.closebtn {
  position: absolute;
  top: 10px;
  right: 15px;
  color: white;
  font-size: 35px;
  cursor: pointer;
}

--></style>
<div class="rowimg">
  <img class="columnimg "src="https://upload.wikimedia.org/wikipedia/commons/e/e0/SNice.svg"">
</div>

标签: javascripthtmlcss

解决方案


推荐阅读