问题描述
我正在 Hugo 中建立一个网站。我正在使用 hello friend ng 主题。我想向主站点添加一个 svg 图像,但我希望它根据所选主题是浅色还是深色而改变。
该主题切换由 theme.js
处理:
const theme = window.localStorage && window.localStorage.getItem("theme");
const themetoggle = document.querySelector(".theme-toggle");
const isDark = theme === "dark";
var MetaThemeColor = document.querySelector("Meta[name=theme-color]");
if (theme !== null) {
document.body.classList.toggle("dark-theme",isDark);
isDark
? MetaThemeColor.setAttribute("content","#252627")
: MetaThemeColor.setAttribute("content","#fafafa");
}
themetoggle.addEventListener("click",() => {
document.body.classList.toggle("dark-theme");
window.localStorage &&
window.localStorage.setItem(
"theme",document.body.classList.contains("dark-theme") ? "dark" : "light"
);
document.body.classList.contains("dark-theme")
? MetaThemeColor.setAttribute("content","#fafafa");
});
但我不知道如何访问它正在使用的变量。
解决方法
我没有设法做到这一点,但我找到了一种满足我需求的解决方法,所以我将其发布,以防有人认为它有价值。
我决定使用 <img>
并将我的图像内容复制到那里,而不是使用带有指向不同 svg 图像的链接的 <svg>
,因为它只是 xml。然后,我删除了诸如 stroke
和 fill
之类的属性,将 <svg>
包装在一个 <div
中,并带有一个自定义类,然后我通过 css 控制该类。
我不确定这是否是最好的方法,但它似乎对我有用。