flask从cookie中读取主题模式来设置网站明暗主题切换

昨天我们学习了两种明暗主题切换的方法,但是在SSR渲染的模式下,昨天的切换方法有一个问题,那就是在刷新网站的时候由于使用js读取的color-schema,或者使用js替换class样式的时候都会加载默认的css样式,导致切换到深色主题模式的时候刷新会闪一下浅色模式的样式,很影响查看体验。

昨天的笔记可以直接查看:https://sulao.cn/post/1041

今天我们就记录下从cookie中读取主题模式然后引用不同的样式变量,这样就能解决掉昨天那两种模式的问题,具体操作我们接着看。

首先我们需要定义默认的样式表light.css里面添加一个dark类:

light.css部分内容如下:

:root {
  --light-bg: #fff;
  --light-color: #2f363c;
  --light-code: #fafafa;
  --light-theme: #7d3c4e;
  --light-white: #fff;
  --light-hover: #999;
  --light-border: #ddd;
  --light-headbg: #eee;
  --light-fixed: #2f363c;
}
body{
    font-size: 14px !important;
    margin: 0;
    padding: 0;width: 100%;
    height: 100%;
    font-family: 'Century Gothic','Microsoft Yahei',tahoma,Arial;
    background-color: var(--light-theme);
    color: var(--light-color);
    transition: background-color 0.3s ease, color 0.3s ease;
}
.row-bg{
    background-color: var(--light-bg);
    opacity: 0.95;
}
.dark{
  --light-bg: #2f363c;
  --light-color: #fff;
  --light-code: #fafafa;
  --light-theme: #7d3c4e;
  --light-white: #fff;
  --light-hover: #999;
  --light-border: #ddd;
  --light-headbg: #eee;
  --light-fixed: #2f363c;
}
注意dark类中需要切换的颜色的变量重新赋不一样的值即可,其他不需要变化的默认保持一致

flask视图中我们获取theme并传递到模板,主要在视图的钩子中添加这个功能

#前台视图钩子,限制每秒2次点击
@post.before_request
@limiter.limit("2/second", error_message="Too many requests!")
def post_cache():
#下面两行就是获取主题并传递到模板 theme = request.cookies.get('theme', 'light') g.theme = theme

后端做好了,这样就能直接在前端调用不同的样式,直接在公共模板的头部修改html为如下:

<html{% if g.theme == 'dark' %} class="{{ g.theme }}"{% endif %}>

还需要添加一个javascript的配置方便传递到js文件中进行处理

<script>
    var themeMode = '{{ g.theme }}';
</script>
<script src="{{ url_for('static', filename='js/index.js') }}"></script>

index.js文件就是我们调用的js代码,代码内容如下

var storage = window.localStorage;
function switch_theme(theme){
var isDark = document.documentElement.classList.contains('dark');
if(isDark){
    if(theme == 'light'){
        document.documentElement.classList.remove('dark');
    }else{
        return false;
    }
}else{
    if(theme == 'dark'){
        document.documentElement.classList.add('dark');
    }
}
document.cookie = `theme=${theme}; path=/; max-age=${30 * 24 * 3600}`;
}
storage.theme = themeMode; //从模板中配置的主题模式获取当前主题模式
form.on('switch(switch-theme)', function(data){
    var elem = data.elem;
    var checked = elem.checked;
    console.log(checked);
    if(checked){
        if(storage.theme == 'light'){
            storage.theme = 'dark';
            switch_theme('dark');
        }
    }else{
        if(storage.theme == 'dark'){
            storage.theme = 'light';
            switch_theme('light');
        }
    }
});

我们实现的方式就是通过设置cookie中theme的名字为dark时,将顶部的html添加一个dark的样式,这个样式class名字就作为css的class类变量,然后css通过这个class变量实现样式切换,而刷新网页或者打开新网页的时候就完全是使用对应的样式了。

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://sulao.cn/post/1042

评论列表