使用JavaScript'持久化CSS状态;s的`window.cookie`

Persisting CSS state using JavaScript's `window.cookie`

本文关键字:cookie 状态 window CSS JavaScript 持久化 使用      更新时间:2023-09-26

我发现了一些漂亮的JavaScript,可以反转我网站上的颜色,我找到了一种使用localStorage保持状态的方法。

以下是持久化逻辑的样子:

var isNight = localStorage['night'] || false;
if (isNight) {
   // $html is shorthand for my jQuery selected <html> tag
   $html.addClass('night');
else {
   $html.removeClass('night');
}
// further down I have code that adjusts `localStorage` everytime my button is clicked, inverting the colors

这是可行的,但它看起来非常笨拙,因为每次刷新页面时都可以清楚地看到CSS的变化。

有没有办法让CSS保持上次更改的状态?我想我必须做的是通过JavaScript手动编辑CSS文件,这样当页面加载时,它已经在那里了,但我不知道如何处理。

如果您使用jQuery,我假设这一切都在document.ready中。要在用户看到任何东西之前进行渲染,请有条件地在head元素中添加类:

<html>
<head>
    <!-- Make sure the CSS class is added first -->
    <script>
        var isNight = localStorage["night"] || false;
        if(isNight) document.querySelector("html").className = "night";
    </script>
    <!-- Now load your stylesheet, jQuery & other scripts -->
    <link rel="stylesheet" type="text/css" href="yourstyles.css">
</head>
<body>
</body>
</html>