javascript - 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>
我该怎么做?
解决方案
作为示例,您需要将选择写入 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
推荐阅读
- node.js - 猫鼬中需要路径
- sql - Neo4j Cypher - 等效于 ADD_DATE(date,INTERVAL expr unit)
- azure - Azure Service Fabric:重新部署后台服务时出现超时错误
- spring-boot - 排除微服务的某些组件
- javascript - 设置在对象嵌套 3 级深
- r - 重新排序 ggplot2 geom_bar 中的因子计数数据
- excel - VLOOKUPNTH 单元格显示“#value”
- java - 不断收到 InputMismatchException
- ionic-framework - 选项卡数据未在 ionic 4 中加载动态数据
- haskell - 为什么 Haskell 中的 Functor 类不包含对象函数?是“纯”那个功能吗?