我是一个javascript初学者,我试图集成一个简单的灯光模式按钮。默认的我的网站是黑暗模式。因此,JS/CSS暗光模式工作良好。如果光模式被激活,整个(外部) CSS就会被替换,它看起来真的很棒。
但是,这是我的问题;CSS的当前模式没有保存在本地存储中。因此,当用户移动到下一个HTML页面时,默认的黑暗模式再次出现。
我已经找到了很多(真的)文章/论坛帖子等,并且测试了很多示例代码(合并它们等等)。但他们都没有为我工作。
这里是我的JS代码和HTML/CSS的一小部分。我已经将其分解为各个片段,因为我假设代码片段无法可视化多个HTML/CSS文件,因此您可能需要在本地保存和编辑页面。
当然,我的问题是:我需要在代码中更改什么,以便将当前的Dark/LightMode设置存储在本地存储中,并在页面切换/重新加载上进行访问等等?
谢谢你提前付出的努力!
/这是轻型css /
正文{
字体大小:21;
字体-家庭:塔霍马,日内瓦,无衬线;
最大宽度:550 max;
页边距:0自动;
背景颜色:白色;
}
h1 {
字体大小:30;
颜色:白色;
文本对齐:居中;
文本-阴影:0px0px5px黑色;
边缘:40 px020px0;
}
h2 {
字体大小:20;
颜色:黑色;
文本对齐:居中;
}
..btn切换{
背景:白色;
}
/这是暗模式css /
正文{
字体大小:21;
字体-家庭:塔霍马,日内瓦,无衬线;
最大宽度:550 max;
页边距:0自动;
背景颜色:黑色;
}
h1 {
字体大小:30;
颜色:白色;
文本对齐:居中;
文本-阴影:0px0px5px黑色;
边缘:40 px020px0;
}
h2 {
字体大小:20;
颜色:白色;
文本对齐:居中;
}
..btn切换{
背景:白色;
}
切换暗/光
进入第2站点
切换暗/光
回到1号站点
// JS文件通常是永久链接的
//选择按钮
const =document.querySelector(“. btn -切换”);
//选择样式表
Document.querySelector(“#主题-链接”);
currentTheme =localStorage.getItem(“主题”);
if (currentTheme ==“深色”){
Document.body.classList.toggle(“暗主题”);
}否则if (currentTheme == "light") {
document.body.classList.toggle("light-theme");
}
//侦听按钮上的单击
Btn.addEventListener(“单击”,函数(){
//如果当前URL包含“暗主题. the”
if (theme.getAttribute("href") == "kiblsstyle.css") {
// .然后切换到“轻型主题. then”
theme.href = "kiblsstylelight.css";
//否则..。
}否则{
// .切换到“黑暗主题.dark”
theme.href = "kiblsstyle.css";
}
LocalStorage.setItem(主题,主题);
});
发布于 2022-06-17 16:27:45
您不应该尝试将整个html元素存储在本地存储中。相反,尝试存储主题名称,然后有条件地应用您在本地存储中找到的主题。这是清理后的JS:
const btn = document.querySelector(".btn-toggle");
const styleLink = document.querySelector("#theme-link");
// Get stored theme with fallback value
const currentTheme = localStorage.getItem("theme") || "light";
if (currentTheme === "dark") styleLink.href = "kiblsstyle.css";
else if (currentTheme === "light") styleLink.href = "kiblsstylelight.css";
btn.addEventListener("click", () => {
if (styleLink.getAttribute("href") !== "kiblsstyle.css") {
styleLink.href = "kiblsstyle.css";
localStorage.setItem("theme", "dark");
} else {
styleLink.href = "kiblsstylelight.css";
localStorage.setItem("theme", "light");
}
});发布于 2022-06-17 17:17:23
创建localStorage是为了保存简单的、具有代表性的值,而不是用来存储DOM元素。因此,您可以只保存两个主题的布尔值。(当您创建更多的控件时,只需使用少量的按钮或数组,等等)或者切换主题标题,但不要使用DOM-object。
const theme = document.querySelector("#theme-link");
const currentLightTheme = localStorage.getItem("isLight") || true;
btn.addEventListener("click", function() {
if (!currentLightTheme) {
theme.setAttribute('href', 'kiblsstylelight.css');
} else {
theme.setAttribute('href', 'kiblsstyle.css');
}
localStorage.setItem('isLight', !currentLightTheme)
});https://stackoverflow.com/questions/72662122
复制相似问题