簡體   English   中英

localStorage 屬性不存儲元素的超文本引用屬性

[英]The localStorage property does not store hyptertext reference property of an element

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

您無法將 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()方法。

您只能將字符串作為值存儲在本地存儲中。 您要存儲的任何對象都必須首先使用JSON.stringify進行序列化。 但是,您也不能序列化 DOM 元素。 或者你可以,但你只會得到一個空對象,因為 DOM 元素的所有屬性都存儲在 DOM 元素的原型上,而JSON.stringify只作用於對象自己的屬性,因此你必須執行以下操作:

localStorage.setItem('theme-css', element.href);

您無法將 DOM 元素保存到 LocalStorage。 無論如何,您只能將鏈接安全地作為 LocalStorage 條目。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM