localStorage属性(localStorage.setItem('theme', element);)不存储元素(element.href = '../assets/css/syntax-highlighting/synthwave-84.css';)的href属性:
const lightButton = document.getElementById('theme-light');
const synthwaveButton = document.getElementById('theme-synthwave-84');
const body = document.body;
var check = document.getElementById('theme_css').classList[0] === 'theme-light';
const theme = localStorage.getItem('theme');
var element = document.getElementById('theme_css');
if (theme)
{
body.classList.add(theme);
}
synthwaveButton.onclick = () =>
{
element.href = '../assets/css/syntax-highlighting/synthwave-84.css';
localStorage.setItem('theme', element);
body.classList.replace('theme-dark', 'theme-synthwave-84');
body.classList.replace('theme-light', 'theme-synthwave-84');
body.classList.replace('theme-cyberpunk', 'theme-synthwave-84');
body.classList.replace('theme-tron', 'theme-synthwave-84');
localStorage.setItem('theme', 'theme-synthwave-84');
};HTML:
<link rel="stylesheet" href="../assets/css/syntax-highlighting/suru-plus.css" id="theme_css" />发布于 2020-09-24 06:59:15
不能将DOM元素保存到LocalStorage中。LocalStorage只存储字符串(这很重要!)你甚至不能存储数字或日期)。通常,如果需要保存复杂的数据,人们会存储JSON,但是在这里存储主题名(碰巧是字符串)就足够了。
总的来说,我建议采取一种不同的办法。我会创建一个函数changeTheme(),它使用一个主题名称,并对所有主题使用相同的工作方式,并使用一个对象来存储可用的主题和CSS路径。
const themes = {
"theme-dark": "../assets/css/syntax-highlighting/dark.css",
"theme-light": "../assets/css/syntax-highlighting/light.css",
"theme-cyberpunk": "../assets/css/syntax-highlighting/cyberpunk.css",
"theme-tron": "../assets/css/syntax-highlighting/tron.css",
"theme-synthwave-84": "../assets/css/syntax-highlighting/synthwave-84.css"
};
function changeTheme(newTheme) {
var allThemes = Object.keys(themes);
if (!allThemes.includes(newTheme)) return;
allThemes.forEach(theme => document.body.classList.remove(theme));
document.body.classList.add(newTheme);
document.getElementById('theme_css').href = themes[newTheme];
localStorage.setItem('theme', newTheme);
}
// wire up buttons
document.querySelectorAll('.theme-switch').forEach(button => {
button.onclick = () => changeTheme(button.id);
});
// load saved theme
changeTheme(localStorage.getItem('theme'));与这样的按钮一起,您将有一个没有代码重复的工作主题切换程序。
<button class="theme-switch" id="theme-synthwave-84">Synthwave 84</button>
<button class="theme-switch" id="theme-tron">Tron</button>当然,您可以使用链接而不是按钮,也可以使用其他触发changeTheme()的方法。
发布于 2020-09-24 07:08:26
只能将字符串作为值存储在本地存储中。您想要存储的任何对象都必须首先使用JSON.stringify序列化。但是,您也不能序列化DOM元素。也可以,但您只需要返回一个空对象,因为DOM元素的所有属性都存储在DOM元素的原型上,而JSON.stringify只对对象自身的属性起作用,所以您必须执行以下操作:
localStorage.setItem('theme-css', element.href);发布于 2020-09-24 06:32:16
不能将DOM元素保存到LocalStorage中。无论如何,您只能作为一个LocalStorage条目来保护链接。
https://stackoverflow.com/questions/64040614
复制相似问题