在 cookie 中保存网站样式

saving website styles in cookies

各位。我正在使用 cookie 来保存我的网站颜色样式。用户可以实时更改颜色,并将其保存到他的 cookie 中。在他选择之前,我设置了默认的 css 颜色样式,如下所示 (my.css)

.color-changing{
    background-color: #43A047;
}

工作时可以选择jquery、

的颜色
var panel_theme = $(".color-changing");
    if ($.cookie('background-color')) {
        panel_theme.css("background-color", $.cookie('background-color'));   
    }
    $("#greenColor").click(function () {
        panel_theme.css('background-color', '#43A047');
        $.removeCookie('background-color');
        $.cookie('background-color', '#43A047', {expires: 1, path: '/'});
    });
    $("#redColor").click(function () {
        panel_theme.css('background-color', '#d32f2f');
        $.removeCookie('background-color');
        $.cookie('background-color', '#d32f2f', {expires: 1, path: '/'});
    });

问题是,当您选择与默认颜色不同的颜色时,每次重新加载页面时,您都会看到从默认颜色到选择颜色的快速闪烁。我该如何避免这种情况?

我的建议是首先使用 localStorage 而不是 cookie。保存为向服务器发出的每个请求发送的 cookie 负载。

然后将实际的 css 声明保存为样式标记,这样您就可以在 html 完成加载之前将其写入头部。这将防止任何闪烁,因为在呈现 html 时样式已经存在

关闭前类似这样的事情<head>:

<script>
var theme_style = localStorage && localStorage.getItem('theme_style');
if(theme_style){
   document.write(theme_style);
}
</script>

然后设置样式:

function updateUserStyle(color){
    // create style tag
    var style = '<style id="user_style">.color-changing{background-color: '+color + ';}</style>';
    // see if user style tag already exists and replace
    var $currUserStyle =$('#user_style'); 
    if($currUserStyle.length){
       $currUserStyle.replaceWith(style); 
    }else{
        // if didn't exist add to head
        $('head').append(style);
    }
    // store active style
    localStorage.setItem('theme_style', style);

}

用法

$("#redColor").click(function () {
    updateUserStyle('#d32f2f');
});