在初始加载 JS 时设置默认主题
Set default theme on initial load JS
如果 localStorage 中没有先前设置的主题(对于新访问者),我正在尝试将我网站的主题设置为 'theme-dark-purple'。但是,我现在的代码不起作用,我也不知道为什么。
有相应的按钮和 onclick 功能来设置每个主题,但我没有在这里包括它,因为按钮工作得很好,我不想在这里添加已经工作的代码。
<script>
// 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 default theme as 'theme-dark-purple' if there's no set theme
(function () {
if (localStorage.getItem('theme') != 'theme-dark-purple', 'theme-light-purple', 'theme-dark-blue', 'theme-light-blue') {
setTheme('theme-dark-purple');
}
})();
</script>
其实你写条件的方式是错误的。你可以试试这个。
(function () {
const themes = ['theme-dark-purple', 'theme-light-purple', 'theme-dark-blue', 'theme-light-blue'];
if (!themes.includes(localStorage.getItem('theme'))) {
setTheme('theme-dark-purple');
}
})();
如果 localStorage 中没有先前设置的主题(对于新访问者),我正在尝试将我网站的主题设置为 'theme-dark-purple'。但是,我现在的代码不起作用,我也不知道为什么。
有相应的按钮和 onclick 功能来设置每个主题,但我没有在这里包括它,因为按钮工作得很好,我不想在这里添加已经工作的代码。
<script>
// 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 default theme as 'theme-dark-purple' if there's no set theme
(function () {
if (localStorage.getItem('theme') != 'theme-dark-purple', 'theme-light-purple', 'theme-dark-blue', 'theme-light-blue') {
setTheme('theme-dark-purple');
}
})();
</script>
其实你写条件的方式是错误的。你可以试试这个。
(function () {
const themes = ['theme-dark-purple', 'theme-light-purple', 'theme-dark-blue', 'theme-light-blue'];
if (!themes.includes(localStorage.getItem('theme'))) {
setTheme('theme-dark-purple');
}
})();