JavaScript 在用户缓存中选择

标签 javascript html

我有一个脚本:

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

我该怎么做?

最佳答案

您需要将选择写入 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

关于JavaScript 在用户缓存中选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60421732/

相关文章:

javascript - 在 Angular 或 Node 中创建报告?生成 HTML 客户端还是服务器端?

html - 通过从表单选择选项中选择的按钮按下打开链接

jquery - 没有文字时如何去除边框

javascript - jQuery如何将一个元素的所有内容替换为另一个元素?

javascript - 无法使用 removeChild 从 html 正文中删除元素

javascript - 更新 div 内的计时器。 JavaScript

javascript - 向所有元素添加单击事件监听器 - Firefox 插件

jquery - 当 if 语句正确时显示一个新的 <p> 元素

html - 如何在 CSS 中相对于父项定位子项?

javascript - 无法读取未定义的属性 'routeName' - react 抽屉导航