今天教大家如何如何做同款夜间模式!夜间模式为了迎合夜晚,让你从视觉上感到光线变暗,就会想办法把屏幕变暗,这样屏幕整的亮度和夜间环境更接近,就能让你在晚上浏览网站不那么辣眼睛。

那么好教程开始

首先,我们需要在主题模板中打开“footer.php”文件,在“”前添加如下代码:

<script type="text/javascript">
function switchNightMode(){
    var night = document.cookie.replace(/(?:(?:^|.*;s*)nights*=s*([^;]*).*$)|^.*$/, "$1") || '0';
    if(night == '0'){
        document.body.classList.add('night');
        document.cookie = "night=1;path=/"
        console.log('夜间模式开启');
    }else{
        document.body.classList.remove('night');
        document.cookie = "night=0;path=/"
        console.log('夜间模式关闭');
    }
}
</script>

保存文件即可,如果想要实现自动切换夜间模式,那么直接复制如下代码:

<script type="text/javascript">
function switchNightMode(){
    var night = document.cookie.replace(/(?:(?:^|.*;s*)nights*=s*([^;]*).*$)|^.*$/, "$1") || '0';
    if(night == '0'){
        document.body.classList.add('night');
        document.cookie = "night=1;path=/"
        console.log('夜间模式开启');
    }else{
        document.body.classList.remove('night');
        document.cookie = "night=0;path=/"
        console.log('夜间模式关闭');
    }
} (function(){
    if(document.cookie.replace(/(?:(?:^|.*;s*)nights*=s*([^;]*).*$)|^.*$/, "$1") === ''){
        if(new Date().getHours() > 22 || new Date().getHours() < 5){
            document.body.classList.add('night');
            document.cookie = "night=1;path=/";
            console.log('夜间模式自动开启');
        }else{
            document.body.classList.remove('night');
            document.cookie = "night=0;path=/";
            console.log('夜间模式自动关闭');
        }
    }else{
        var night = document.cookie.replace(/(?:(?:^|.*;s*)nights*=s*([^;]*).*$)|^.*$/, "$1") || '0';
        if(night == '0'){
            document.body.classList.remove('night');
        }else if(night == '1'){
            document.body.classList.add('night');
        }
    }
})();</script>

代码中的 22 和 5 就是晚上22点开始到第二天的5点结束,其实这段代码并不严谨,为什么这么说呢?此代码是针对没有记录cookies的网站来说有效,一旦手动开启或者关闭过夜间模式,那么这个自动是失效了,除非清空浏览器的cookies,总之这里目前没有办法完美适配(我技术不行),其实我们可以在js做个判断,就是每天的22点时候判断cookies是否是夜间模式,如果不是,弹出对话框询问是否开启夜间模式,如果是就不提示。然后打开网站的“header.php”文件,我们需要给网站填写一个按钮,以此来手动开启和关闭夜间模式:

<a class="at-night" href="javascript:switchNightMode()" target="_self"></a>

复制如上代码,放在你认为合适的地方,然后保存,登录后台,清空主题模板缓存编译,然后打开首页,测试夜间模式是否有效。其实教程到这才算是完成一般,因为你在测试的过程中会发现,开启夜间模式并没有效果,,,嗯嗯是的,因为你们没有适配夜间模式的css,这个教程写不出,因为每个主题模板的div框架和css命名不同,无法统一,所以需要您自己去查找对应的class类,然后添加夜间模式的样式,例如:

body.night DIV名称 {background-color: #263238;color: #aaa; }

其他程序(TP5或者Typecho等)使用这个:

<body class="<?php echo($_COOKIE['night'] == '1' ? 'night' : ''); ?>">

这样就解决闪屏的BUG了,当检测到cookie相关字段时直接输出body的class为night,就可以已防止页面闪烁