给你的网站增加一个黑夜模式

前言

晚上时候看网站,背景太白容易让眼睛感到疲劳,但是如果能让网站加一个黑夜模式,眼睛看着就会舒适很多

QQ图片20221122223257

教程开始

打开主题文件,找到“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,就可以已防止页面闪烁

其他主题网页自行修改即可

© 版权声明
THE END
喜欢就支持一下吧
点赞2赞赏 分享
评论 抢沙发
头像
欢迎您留下宝贵的见解!
提交
头像

昵称

取消
昵称表情代码图片

    暂无评论内容