英文:
2 javascript functions using localStorage causing troubles
问题
I want my visitors to choose between 4 background colors in light mode or to just turn dark mode on.
My first script changes the background color of BODY-tag without problem, but when using together with my second javascript to turn on dark mode it just causes problem and only dark/light mode works. I think there must be some kind of problem with the localstorage function but I am very new to Javascript and I really can not make them work.
Here is the HTML:
#// These divs changes the color of body in white/light mode
<div class="coeleste" onclick="setBackground('#ECF3F9')">Elegant</div>
<div class="viridis" onclick="setBackground('#F1F9EC')">Modern</div>
<div class="rubrum" onclick="setBackground('#F2EBDD')">Classic</div>
<div class="initialis" onclick="setBackground('#FFFFFF')">Default</div>
#// And this div changes the color of body to dark/light mode
<div class="luminaria"><a id="modus" href="#">TURN OFF THE LIGHTS</a></div>
Here is the javascript first part to change the color of body background in light mode. it is simple but it works alone
function setBackground(color)
{
localStorage.setItem("name", color);
window.location.href = '#'; //reload the page to effect the change.
}
if(localStorage.name) //Accessing name variable of localStorage.
{
document.body.style.background = localStorage.name;
}
And here is the function to set dark mode on/off, when working alone it works fine too, but when using the javascript from above and this one together then only this dark mode works but not the first one
//second javascript
var modus = document.getElementById("modus"),
corpus = document.getElementsByTagName("body")[0];
modus.addEventListener("click", function () {
var o, s;
corpus.classList.contains("luccious")
? (corpus.classList.remove("luccious"),
(modus.textContent = "TURN OFF THE LIGHTS"),
(o = "#FFFFFF"),
(s = "#121212"))
: (corpus.classList.add("luccious"),
(modus.textContent = "TURN ON THE LIGHTS"),
(o = "#121212"),
(s = "#FFFFFF")),
(corpus.style.backgroundColor = o),
(corpus.style.color = s),
localStorage.setItem("albus", o),
localStorage.setItem("umbra", s);
});
var lux = localStorage.getItem("albus"),
umbris = localStorage.getItem("umbra");
lux &&
umbris &&
((corpus.style.backgroundColor = lux),
(corpus.style.color = umbris),
"#121212" === lux &&
"#FFFFFF" === umbris &&
(corpus.classList.add("luccious"),
(modus.textContent = "TURN OFF THE LIGHTS")));
I created this Codepen to see it in action
https://codepen.io/familias/pen/VwVKzrq
Any idea what is causing the first one not to work and how to fix that?
英文:
I want my visitors to choose between 4 background colors in light mode or to just turn dark mode on.
My first script changes the background color of BODY-tag without problem, but when using together with my second javascript to turn on dark mode it just causes problem and only dark/light mode works. I think there must be some kind of problem with the localstorage function but I am very new to Javascript and I really can not make them work.
Here is the HTML:
#// These divs changes the color of body in white/light mode
<div class="coeleste" onclick="setBackground('#ECF3F9')">Elegant</div>
<div class="viridis" onclick="setBackground('#F1F9EC')">Modern</div>
<div class="rubrum" onclick="setBackground('#F2EBDD')">Classic</div>
<div class="initialis" onclick="setBackground('#FFFFFF')">Default</div>
#// And this div changes the color of body to dark/light mode
<div class="luminaria"><a id="modus" href="#">TURN OFF THE LIGHTS</a></div>
Here is the javascript first part to change the color of body background in light mode. it is simple but it works alone
function setBackground(color)
{
localStorage.setItem("name", color);
window.location.href = '#'; //reload the page to effect the change.
}
if(localStorage.name) //Accessing name variable of localStorage.
{
document.body.style.background = localStorage.name;
}
And here is the function to set dark mode on/off, when working alone it works fine too, but when using the javascript from above and this one together then only this dark mode works but not the first one
//second javascript
var modus = document.getElementById("modus"),
corpus = document.getElementsByTagName("body")[0];
modus.addEventListener("click", function () {
var o, s;
corpus.classList.contains("luccious")
? (corpus.classList.remove("luccious"),
(modus.textContent = "TURN OFF THE LIGHTS"),
(o = "#FFFFFF"),
(s = "#121212"))
: (corpus.classList.add("luccious"),
(modus.textContent = "TURN ON THE LIGHTS"),
(o = "#121212"),
(s = "#FFFFFF")),
(corpus.style.backgroundColor = o),
(corpus.style.color = s),
localStorage.setItem("albus", o),
localStorage.setItem("umbra", s);
});
var lux = localStorage.getItem("albus"),
umbris = localStorage.getItem("umbra");
lux &&
umbris &&
((corpus.style.backgroundColor = lux),
(corpus.style.color = umbris),
"#121212" === lux &&
"#FFFFFF" === umbris &&
(corpus.classList.add("luccious"),
(modus.textContent = "TURN OFF THE LIGHTS")));
I created this Codepen to see it in action
https://codepen.io/familias/pen/VwVKzrq
Any idea what is causing the first one not to work and how to fix that?
答案1
得分: 0
根据评论更新的答案
为了使这个工作起来,我们需要做以下步骤
- 定义主题选择器,如果你使用了太多颜色(比如你当前的按钮),你需要在切换浅色/深色主题时更改按钮颜色(特别是字体颜色),我建议使用一个HTML选择器
- 删除那些按钮,改为使用选择器
- 删除CSS,因为我们不再使用按钮
- 当你使用浅色主题时,将字体颜色改为黑色,当使用深色主题时,将字体颜色改为白色
- 现在我们有了一个选择器,我们需要为它添加一个事件监听器(用于处理颜色选择器的更改)
- 我们可以只有一个函数来实现在加载、更改选择器或在我们的localStorage中没有颜色的情况下设置颜色
const selector = document.querySelector("#themeSelector");
function setBackground(color) {
localStorage.setItem("colorName", color);
document.body.style.background = color;
if (color === "#000000") {
document.body.style.color = "#FFFFFF";
} else {
document.body.style.color = "#000000";
}
}
if (localStorage.getItem("colorName")) {
const color = localStorage.getItem("colorName");
selector.value = color;
setBackground(color);
} else {
setBackground(selector.value);
}
selector.addEventListener("change", (event) => {
setBackground(event.target.value);
});
<label>Choose a theme</label>
<select id="themeSelector">
<option value='#ECF3F9'>Elegant</option>
<option value='#F1F9EC'>Modern</option>
<option value='#F2EBDD'>Classic</option>
<option value='#FFFFFF'>Default</option>
<option value='#000000'>Dark</option>
</select>
<p>Lorem Ipsum es simplemente el texto de relleno de las imprentas y archivos de texto. Lorem Ipsum ha sido el texto de relleno estándar de las industrias desde el año 1500, cuando un impresor (N. del T. persona que se dedica a la imprenta) desconocido usó una galería de textos y los mezcló de tal manera que logró hacer un libro de textos especimen. No sólo sobrevivió 500 años, sino que también ingresó como texto de relleno en documentos electrónicos, quedando esencialmente igual al original. Fue popularizado en los 60s con la creación de las hojas "Letraset", las cuales contenían pasajes de Lorem Ipsum, y más recientemente con software de autoedición, como por ejemplo Aldus PageMaker, el cual incluye versiones de Lorem Ipsum.</p>
请注意,当使用localStorage时,它会持续很长时间,因此如果你在测试,首先在下一次尝试之前通过控制台删除它localStorage.removeItem("yourItemId")
这是在CodePen中的代码,请记住,这只是一个实现你需要的指南:
https://codepen.io/jwohllk/pen/LYXROjW
英文:
Updated answer based on comments
In order to set this working we need to do the following
- Define the theme selector, if you use something that has too many colors (Like your current buttons) you will need change button colors (specially font color) each time you switch between light/dark, I will recommend to use a html selector
- Remove those buttons and change it by a selector
- Remove CSS as we are not using the buttons
- When you use light themes change font color in black, when using dark theme change font color white
- Now that we have a selector we need to add an event listener to it (for handling color selector change)
- We can have only one function to achieve the color set in case of load, change the selector or when we don't have a color in our localStorage
const selector = document.querySelector("#themeSelector");
function setBackground(color) {
localStorage.setItem("colorName", color);
document.body.style.background = color;
if (color === "#000000") {
document.body.style.color = "#FFFFFF";
} else {
document.body.style.color = "#000000";
}
}
if (localStorage.getItem("colorName")) {
const color = localStorage.getItem("colorName");
selector.value = color;
setBackground(color);
} else {
setBackground(selector.value);
}
selector.addEventListener("change", (event) => {
setBackground(event.target.value);
});
<label>Choose a theme</label>
<select id="themeSelector">
<option value='#ECF3F9'>Elegant</option>
<option value='#F1F9EC'>Modern</option>
<option value='#F2EBDD'>Classic</option>
<option value='#FFFFFF'>Default</option>
<option value='#000000'>Dark</option>
</select>
<p>Lorem Ipsum es simplemente el texto de relleno de las imprentas y archivos de texto. Lorem Ipsum ha sido el texto de relleno estándar de las industrias desde el año 1500, cuando un impresor (N. del T. persona que se dedica a la imprenta) desconocido usó una galería de textos y los mezcló de tal manera que logró hacer un libro de textos especimen. No sólo sobrevivió 500 años, sino que tambien ingresó como texto de relleno en documentos electrónicos, quedando esencialmente igual al original. Fue popularizado en los 60s con la creación de las hojas "Letraset", las cuales contenian pasajes de Lorem Ipsum, y más recientemente con software de autoedición, como por ejemplo Aldus PageMaker, el cual incluye versiones de Lorem Ipsum.</p>
Take into account when you use localStorage will last for a long time so if you are testing, first remove it by console before your next try localStorage.removeItem("yourItemId")
Here is the code in codepen, remember that this is only a guide to achieve what you need:
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论