fix: pdf backgorund

This commit is contained in:
hyper
2026-02-27 21:42:48 +08:00
parent 7e95c44d8d
commit da1e11fb74
2 changed files with 16 additions and 25 deletions
+14 -23
View File
@@ -1,5 +1,5 @@
import { customElement, noShadowDOM } from "solid-element";
import { createEffect, createResource } from "solid-js";
import {createEffect, onCleanup} from "solid-js";
import { resolvePath } from "./utils/path";
export interface BgProps {
@@ -18,34 +18,25 @@ customElement("md-bg", { fit: "cover" }, (props, { element }) => {
}
// 从父节点 article 的 data-src 获取当前 markdown 文件完整路径
const articleEl = element?.closest('article');
const articleEl = element?.closest('article') as HTMLElement;
const articlePath = articleEl?.getAttribute('data-src') || '';
// 解析相对路径
const resolvedSrc = resolvePath(articlePath, rawSrc);
// 加载图片
const loadImage = (src: string): Promise<HTMLImageElement> => {
return new Promise((resolve, reject) => {
const img = new Image();
img.onload = () => resolve(img);
img.onerror = reject;
img.src = src;
});
};
const [image] = createResource(resolvedSrc, loadImage);
createEffect(() => {
// 图片加载完成后,将背景图片设置到 article 元素
if(!articleEl)return;
articleEl.style.backgroundImage = '';
if (image()) {
articleEl.style.backgroundImage = `url(${resolvedSrc})`;
articleEl.style.backgroundSize = props.fit || 'cover';
articleEl.style.backgroundPosition = 'center';
articleEl.style.backgroundRepeat = 'no-repeat';
}
if(!articleEl) return;
articleEl.dataset.mdbg = resolvedSrc;
articleEl.style.backgroundImage = `url(${resolvedSrc})`;
articleEl.style.backgroundSize = props.fit || 'cover';
articleEl.style.backgroundPosition = 'center';
articleEl.style.backgroundRepeat = 'no-repeat';
});
onCleanup(() => {
if(articleEl?.dataset?.mdbg !== resolvedSrc)
return;
articleEl.style.backgroundImage = '';
});
return null;