如何设置和检索 css 到本地存储

How to set and retrieve css to localstorage

我正在尝试使用 javascript 为我的网页创建一个简单的主题选择器。该脚本正在正确更改我的 css 文件,但现在我希望 this.value 保留到本地存储并在选择新文件时更改。让这项工作最简单的方法是什么?

HTML

<head>
    <link id="themeStylesheet" rel="stylesheet" type="text/css" href="css/style_v5.css">
</head>

<form action="./" method="post">
  <select name="themeSelect" id="themeSelect">
     <option value="style_v5">Default</option>
     <option value="ds">ds</option>
     <option value="yo">yo</option>
  </select>
</form>

Javascript

const themeSelect = document.getElementById("themeSelect");
  const themeStylesheet = document.getElementById("themeStylesheet");

  themeSelect.addEventListener("change", function () {
    themeStylesheet.setAttribute("href", "css/" + this.value + ".css");
  });

像这样简单的东西就足够了!阅读有关 Web 存储的更多信息 API on MDN

const themeSelect = document.getElementById("themeSelect");
const themeStylesheet = document.getElementById("themeStylesheet");

function setTheme(theme) {
  themeStylesheet.setAttribute("href", "css/" + theme + ".css");
}

// this just needs to run once on pageload...
if (localStorage.theme) {
  setTheme(localStorage.theme);
}

themeSelect.addEventListener("change", function() {
  setTheme(this.value);
  localStorage.theme = this.value;
});
<head>
  <link id="themeStylesheet" rel="stylesheet" type="text/css" href="css/style_v5.css">
</head>

<form action="./" method="post">
  <select name="themeSelect" id="themeSelect">
    <option value="style_v5">Default</option>
    <option value="ds">ds</option>
    <option value="yo">yo</option>
  </select>
</form>