javascript - 如何将关闭按钮添加到我的灯箱?所以我可以从按钮关闭图片,而不是单击灯箱中的任何位置
问题描述
我正在使用这个简单的灯箱,但我想通过在右上角添加一个关闭按钮来使其更高级。
因此,当它在灯箱中显示图像时,我可以使用关闭按钮将其关闭,而不是单击灯箱中的任何位置来关闭图片。
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>
解决方案
推荐阅读
- java - 如何跨微服务拥有通用 DTO 或实体
- python - 为什么字符串比较不比 Python 中的整数比较快?
- mysql - MariaDB 复制设置后出现重复键错误
- firebase - 通过 Firebase ID 验证用户
- postman - 如何提取原始响应数据并将其添加到邮递员中的环境变量中
- c++ - 类函数可以被线程调用并访问类数据吗?
- gcc - GNU Arm Embedded Toolchain: undefined reference to `__sync_synchronize'
- java - JSON 字符串无效
- xamarin - 有没有办法在没有自定义渲染器的情况下以 xamarin 表单实现 toast 消息
- r - R中带有平均值列的频率表