【发布时间】:2021-09-11 22:56:29
【问题描述】:
我在我的网站上设置了一个颜色主题系统。当你点击一个按钮时,一个类被添加到<html> 并且其对应的主题生效。但是,当我第一次加载我的网站时(我使用隐身模式来模拟这一点),所有主题都不起作用。我想重写我的代码块,基本上说,“当 localStorage 中没有任何内容时,加载'theme-dark-blue'。”
这是我的代码:
// function to set a given theme/color-scheme
function setTheme(themeName) {
localStorage.setItem('theme', themeName);
document.documentElement.className = themeName;
}
// Immediately invoked function to set the theme on initial load
(function () {
if (localStorage.getItem('theme') === 'theme-dark-blue') {
setTheme('theme-dark-blue');
}
})();
目前为止的其他主题是“theme-light-blue”和“theme-dark-green”。我正在考虑尝试将其表述为“如果<html> 没有课程,请设置'theme-dark-blue'”
【问题讨论】:
-
那为什么不直接这样做:""当localStorage 中没有任何内容时,加载'theme-dark-blue'。"" ?
if(localStorage.getItem('theme') === null)... -
@EmrysMayell Doe 以下答案解决了您的问题吗?