Added image preview

This commit is contained in:
ClovertaTheTrilobita 2026-04-25 01:05:50 +03:00
parent d30148c021
commit 64b2a2952b
3 changed files with 99 additions and 0 deletions

View file

@ -81,6 +81,11 @@ const t = getTranslations(lang);
<slot />
</div>
<dialog id="image-preview-dialog" class="image-preview-dialog">
<button class="image-preview-close" aria-label="关闭图片预览">×</button>
<img id="image-preview-img" alt="" />
</dialog>
<PostNav post={post} lang={lang} />
<h2>{comments}</h2>
@ -116,6 +121,42 @@ const t = getTranslations(lang);
})}
/>
<script is:inline>
function initImagePreview() {
const dialog = document.getElementById("image-preview-dialog");
const previewImg = document.getElementById("image-preview-img");
const closeBtn = dialog?.querySelector(".image-preview-close");
if (!dialog || !previewImg || !closeBtn) return;
document.querySelectorAll("article img").forEach((img) => {
if (img.dataset.previewBound === "true") return;
img.dataset.previewBound = "true";
img.addEventListener("click", () => {
previewImg.src = img.currentSrc || img.src;
previewImg.alt = img.alt || "";
dialog.showModal();
});
});
closeBtn.addEventListener("click", () => {
dialog.close();
previewImg.removeAttribute("src");
});
dialog.addEventListener("click", (event) => {
if (event.target === dialog) {
dialog.close();
previewImg.removeAttribute("src");
}
});
}
document.addEventListener("DOMContentLoaded", initImagePreview);
document.addEventListener("astro:page-load", initImagePreview);
</script>
<script>
const initFloatingActions = () => {
const backButton = document.getElementById("back-button");

57
src/styles/dialog.css Normal file
View file

@ -0,0 +1,57 @@
.image-preview-dialog {
padding: 0;
border: none;
background: transparent;
max-width: min(96vw, 1200px);
max-height: 96vh;
}
.image-preview-dialog::backdrop {
background: rgba(0, 0, 0, 0.72);
backdrop-filter: blur(6px);
}
.image-preview-dialog img {
display: block;
max-width: 96vw;
max-height: 90vh;
object-fit: contain;
border-radius: 16px;
box-shadow: 0 20px 80px rgba(0, 0, 0, 0.45);
}
.image-preview-close:focus {
outline: none;
}
.image-preview-close:focus-visible {
outline: 2px solid rgba(125, 162, 255, 0.9);
outline-offset: 4px;
}
.image-preview-close {
position: fixed;
top: 1.25rem;
right: 1.25rem;
z-index: 1;
width: 2.4rem;
height: 2.4rem;
border: none;
border-radius: 999px;
background: transparent;
color: var(--text-color-dark);
font-size: 2.6rem;
line-height: 1;
cursor: pointer;
}
/* .image-preview-close:hover {
background: rgba(0, 0, 0, 0.75);
} */
/* 给文章图片一个可点击提示 */
.prose img,
.markdown-body img,
article img {
cursor: zoom-in;
}

View file

@ -3,6 +3,7 @@
@import url("https://unpkg.com/@fontsource/maple-mono@5.2.6/700.css");
@import "./latest-comments.css";
@import "./variables.css";
@import "./dialog.css";
pre {
padding: 1rem;