【问题标题】:saving website styles in cookies在 cookie 中保存网站样式
【发布时间】:2015-05-06 02:29:02
【问题描述】:

每个人。我正在使用 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: '/'});
    });

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

【问题讨论】:

    标签: javascript jquery html css cookies


    【解决方案1】:

    我的建议是首先使用 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');
    });
    

    【讨论】:

    • 如何将其保存在客户端计算机上?它不应该依赖于服务器。结果我不明白你的意思是“localStorage”。我无法为每个不合理使用的用户保存主题。因为在这种情况下,我应该重写页面。
    • 那是用户机器……它是浏览器的一部分
    • 以及如何在没有cookie的情况下保存它?请给我一个例子
    • 例子?我给了你答案的代码。你还需要什么例子?你试过了吗?
    • 我这样做了,但是我使用了 cookie 而不是 localstorage。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2019-08-20
    • 1970-01-01
    • 2016-09-06
    • 1970-01-01
    • 1970-01-01
    • 2017-10-05
    • 2016-04-13
    • 1970-01-01
    相关资源
    最近更新 更多