Lightbox 效果是网页中常见的效果,尤其是在图片展示中,它可以让用户以更大的尺寸、更好的画质查看图片,带来刚好的用户体验。今天,我们使用 HTML5 的 dialog 标签制作一个简单好用的 lightbox 效果。
制作过程
1、引入文件
<link rel="stylesheet" href="css/normalize.min.css">
2、HTML
<div class="dowebok">
<img src="images/1-1.jpg" alt="">
<img src="images/1-2.jpg" alt="">
<img src="images/1-3.jpg" alt="">
<img src="images/1-4.jpg" alt="">
<img src="images/1-5.jpg" alt="">
<img src="images/1-6.jpg" alt="">
<img src="images/1-7.jpg" alt="">
<img src="images/1-1.jpg" alt="">
<img src="images/1-2.jpg" alt="">
<img src="images/1-3.jpg" alt="">
<img src="images/1-4.jpg" alt="">
<img src="images/1-5.jpg" alt="">
<img src="images/1-6.jpg" alt="">
<img src="images/1-7.jpg" alt="">
</div>
3、CSS
.dowebok {
display: grid;
gap: 1rem;
grid-template-columns: repeat(4, 1fr);
grid-auto-flow: row dense;
width: 90%;
margin: auto;
}
.dowebok img {
max-width: 100%;
height: auto;
}
.dowebok > :nth-child(7n + 1) {
grid-column: span 2;
grid-row: span 2;
}
.dowebok img {
display: block;
aspect-ratio: 1/1;
border-radius: 6px;
-o-object-fit: cover;
object-fit: cover;
overflow: hidden;
}
dialog.lightbox {
border: none;
padding: 0;
-webkit-animation: fadeIn 0.3s ease-out;
animation: fadeIn 0.3s ease-out;
background-color: transparent;
}
dialog.lightbox::-webkit-backdrop {
background-color: rgba(0, 0, 0, 0.4);
}
dialog.lightbox::backdrop {
background-color: rgba(0, 0, 0, 0.4);
}
dialog.lightbox img {
-o-object-fit: contain;
object-fit: contain;
display: block;
overflow: hidden;
height: 100%;
width: 100%;
max-width: 90vw;
max-width: 90dvw;
max-height: 90vh;
max-height: 90dvh;
border-radius: 6px;
}
@-webkit-keyframes fadeIn {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
@keyframes fadeIn {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
4、Javascript
document.querySelectorAll('.dowebok img').forEach((img) => {
img.addEventListener('click', (e) => {
// 创建 dialog
const dialog = document.createElement('dialog')
dialog.className = 'lightbox'
// 克隆 img 并放入 dialog 中
const imgClone = img.cloneNode()
dialog.appendChild(imgClone)
// 把 dialog 插入到 body 中
document.body.appendChild(dialog)
dialog.showModal()
document.body.setAttribute('inert', true)
// 关闭 dialog 事件
dialog.addEventListener('click', (e) => {
if (e.target === e.currentTarget) {
dialog.close()
}
})
// dialog 关闭方法
dialog.addEventListener('close', (e) => {
dialog.parentNode.removeChild(dialog)
document.body.removeAttribute('inert')
})
})
})
到这里就制作完了,看看效果吧:https://www.dowebok.com/demo/9901/
网友评论