简体   繁体   English

在Cookie中保存网站样式

[英]saving website styles in cookies

everyone. 大家。 I'm using a cookie to save my website color style. 我正在使用cookie来保存我的网站颜色样式。 The user can change color in real time and it will saved into his cookies. 用户可以实时更改颜色,并将其保存到他的cookie中。 Before his choice I set default css color style like this (my.css) 在选择之前,我先设置了默认的CSS颜色样式(my.css)

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

when you working you can choose the color with jquery, 当您工作时,可以使用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: '/'});
    });

The problem is that when you choose the color which is different from default color, with every page reload you will see the very fast flicker from default color to choosen. 问题在于,当您选择与默认颜色不同的颜色时,每次重新加载页面时,您都会看到从默认颜色到所选颜色的闪烁非常快。 How I can avoid this? 我如何避免这种情况?

My suggestion would be first to use localStorage instead of cookie. 我的建议是首先使用localStorage而不是cookie。 Saves cookie payload that gets sent for each and every request made to server. 保存Cookie的有效负载,该负载将针对服务器的每个请求发送。

Then save the actual css declaration as a style tag so you can write it in the head before the html has even finished loading. 然后将实际的css声明另存为样式标签,以便您可以在html加载完成之前将其写在头部。 This will prevent any flicker as the style will already exist as html is rendered 这将防止任何闪烁,因为在呈现html时样式将已经存在

Something like this before closing <head> : 在关闭<head>之前是这样的:

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

Then to set style: 然后设置样式:

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);

}

Usage 用法

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM