feat: 文章图片预览

This commit is contained in:
2026-07-17 18:24:01 +08:00
parent c7766edb01
commit 9909d8d7a5
3 changed files with 75 additions and 1 deletions

View File

@@ -1,6 +1,7 @@
---
import "@/styles/github-markdown.css"
import "@/styles/github-markdown-reset.css"
import "photoswipe/dist/photoswipe.css";
import Layout from "@/layouts/Layout.astro";
import {createHttp} from "@/lib/request.ts";
@@ -98,6 +99,11 @@ const published_at = formatDatetime(data.published_at, 'YYYY 年 M 月 D 日')
box-shadow: rgba(149, 157, 165, 0.2) 0 2px 14px -4px;
}
:global(.post.markdown-body img) {
object-fit: contain;
height: auto !important;
}
.post-view {
display: flex;
align-items: center;
@@ -124,8 +130,66 @@ const published_at = formatDatetime(data.published_at, 'YYYY 年 M 月 D 日')
}
}
:global(.dark) .post{
:global(.dark) .post {
background: #090b0c;
box-shadow: rgba(255, 255, 255, 0.5) 0 0px 10px -4px;
}
</style>
<script>
import PhotoSwipeLightbox from "photoswipe/lightbox"
const init = async () => {
const post = document.querySelector('.post')!
const images = Array.from(post.querySelectorAll('img'))
const waitImageLoaded = (img: HTMLImageElement) => {
if (img.complete && img.naturalWidth > 0 && img.naturalHeight > 0) {
return Promise.resolve()
}
return new Promise<void>((resolve) => {
img.addEventListener("load", () => resolve(), {once: true})
img.addEventListener("error", () => resolve(), {once: true})
})
}
await Promise.all(
images.map(async (img) => {
if (img.closest("a")) return
await waitImageLoaded(img)
const link = document.createElement("a")
link.href = img.currentSrc || img.src
link.target = "_blank"
link.rel = "noreferrer"
link.dataset.pswpWidth = String(img.naturalWidth || img.width || 1200)
link.dataset.pswpHeight = String(img.naturalHeight || img.height || 800)
img.parentNode?.insertBefore(link, img)
link.appendChild(img)
})
)
const lightbox = new PhotoSwipeLightbox({
gallery: ".post",
children: "a",
pswpModule: () => import("photoswipe"),
padding: {
top: 48,
right: 24,
bottom: 48,
left: 24,
},
bgOpacity: 0.5,
})
lightbox.init()
}
init()
</script>