我有一个脚本:
<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/