localStorage 属性不存储元素的超文本引用属性

属性localStorage( localStorage.setItem('theme', element);) 不存储href元素 ( element.href = '../assets/css/syntax-highlighting/synthwave-84.css';) 的属性:


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" />


慕虎7371278
浏览 164回答 3
3回答

森栏

您不能将 DOM 元素保存到 LocalStorage。LocalStorage 仅存储字符串(这很重要!您甚至不能存储数字或日期)。通常,如果需要保存复杂数据,人们会存储 JSON,但这里存储主题名称(恰好是一个字符串)就足够了。总的来说,我会推荐一种不同的方法。我会制作一个函数changeTheme(),它采用主题名称并对所有主题都相同,并使用一个对象来存储可用的主题和 CSS 路径。const themes = {&nbsp; "theme-dark": "../assets/css/syntax-highlighting/dark.css",&nbsp; "theme-light": "../assets/css/syntax-highlighting/light.css",&nbsp; "theme-cyberpunk": "../assets/css/syntax-highlighting/cyberpunk.css",&nbsp; "theme-tron": "../assets/css/syntax-highlighting/tron.css",&nbsp; "theme-synthwave-84": "../assets/css/syntax-highlighting/synthwave-84.css"};function changeTheme(newTheme) {&nbsp; var allThemes = Object.keys(themes);&nbsp; if (!allThemes.includes(newTheme)) return;&nbsp; allThemes.forEach(theme => document.body.classList.remove(theme));&nbsp; document.body.classList.add(newTheme);&nbsp; document.getElementById('theme_css').href = themes[newTheme];&nbsp; localStorage.setItem('theme', newTheme);}// wire up buttonsdocument.querySelectorAll('.theme-switch').forEach(button => {&nbsp; button.onclick = () => changeTheme(button.id);});// load saved themechangeTheme(localStorage.getItem('theme'));与这样的按钮一起,您将拥有一个没有代码重复的工作主题切换器。<button class="theme-switch" id="theme-synthwave-84">Synthwave 84</button><button class="theme-switch" id="theme-tron">Tron</button>当然你可以使用链接代替按钮,或者changeTheme()你能想到的任何其他触发方式。

侃侃尔雅

您只能将字符串作为值存储在本地存储中。您要存储的任何对象都必须首先使用JSON.stringify.&nbsp;但是,您也不能序列化 DOM 元素。或者你可以,但是你只会得到一个空对象,因为 DOM 元素的所有属性都存储在 DOM 元素的原型上,并且JSON.stringify只作用于对象自己的属性,所以你必须做类似的事情:localStorage.setItem('theme-css',&nbsp;element.href);

海绵宝宝撒

您不能将 DOM 元素保存到 LocalStorage。无论如何,您只能将链接保护为 LocalStorage 条目。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript