保存网站样式中的cookie



大家。我正在使用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');
});

最新更新