首页 > 解决方案 > JavaScript 在用户缓存中选择

问题描述

我有一个脚本:

<script>
function swapStyleSheet(sheet){
    document.getElementById('pagestyle').setAttribute('href', sheet);
}
</script>

我希望浏览器在缓存中记住用户选择的选项,例如。如果选择深色,则始终使用 dark.css 打开网站

<button onclick="swapStyleSheet('dark.css')">Dark</button>
<button onclick="swapStyleSheet('style.css')">Light</button>

我该怎么做?

标签: javascripthtml

解决方案


作为示例,您需要将选择写入 LocalStorage。

有关它的文档,请参阅https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API/Local_storage。请记住在尝试使用它之前先检查它是否存在于用户的浏览器中。

编辑,这是一个例子:

// Write to LocalStorage when clicking a button
if (window.localStorage) {
   localStorage.setItem("theme", "dark");
}

// Read the theme from localStorage
if (window.localStorage) {
   const theme = localStorage.getItem("theme");
   // do something with the theme
}

但是:我可以建议一种比使用 CSS 变量/自定义属性加载不同样式表更好的方法吗?

这是如何实现这一目标的一个示例:https ://dev.to/ananyaneogi/create-a-dark-light-mode-switch-with-css-variables-34l8


推荐阅读