直接贴代码了哟。
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Document</title> <style> .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; } } </style> </head> <body> <div> <img src="1.jpg" alt=""> <img src="1.jpg" alt=""> <img src="1.jpg" alt=""> <img src="1.jpg" alt=""> <img src="1.jpg" alt=""> <img src="1.jpg" alt=""> <img src="1.jpg" alt=""> <img src="1.jpg" alt=""> <img src="1.jpg" alt=""> <img src="1.jpg" alt=""> </div> <script> 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') }) }) }) </script> </body> </html>