纯 js + css 开启网站白天/黑夜模式

chen'mo
2021-06-09 / 1 评论 / 2,820 阅读 / 正在检测是否收录...
温馨提示:
本文最后更新于2021年06月08日,已超过1052天没有更新,若内容或图片失效,请留言反馈。

最近看到很多网站都加了暗黑模式,可能主要是因为手机的原因吧,我之前一直不屑这个功能,直到昨天晚上,我给手机开启晚间深色模式后,打开我的网站,真的刺眼,所以就给胖蒜网加上了。
我采用的是最普通的js+css的模式,代码也是参考网上的,所以就分享出来。

一、JS部分代码

<script type = "text/javascript" >
function switchNightMode(){
    var night = document.cookie.replace(/(?:(?:^|.*;\s*)night\s*\=\s*([^;]*).*$)|^.*$/, "$1") || '0';
    if(night == '0'){
        document.querySelector('link[title="dark"]').disabled = true;
        document.querySelector('link[title="dark"]').disabled = false;
        document.cookie = "night=1;path=/"
        console.log('夜间模式开启');
    }else{
        document.querySelector('link[title="dark"]').disabled = true;
        document.cookie = "night=0;path=/"
        console.log('夜间模式关闭');
    }
}

//指定时间进入夜间模式
(function(){
    if(document.cookie.replace(/(?:(?:^|.*;\s*)night\s*\=\s*([^;]*).*$)|^.*$/, "$1") === ''){
        if(new Date().getHours() > 22 || new Date().getHours() < 6){
        document.querySelector('link[title="dark"]').disabled = true;
        document.querySelector('link[title="dark"]').disabled = false;
        document.cookie = "night=1;path=/"
        console.log('夜间模式开启');
        }else{
        document.cookie = "night=0;path=/"
        console.log('夜间模式关闭');
        }
    }else{
        var night = document.cookie.replace(/(?:(?:^|.*;\s*)night\s*\=\s*([^;]*).*$)|^.*$/, "$1") || '0';
        if(night == '0'){
        document.querySelector('link[title="dark"]').disabled = true;
        console.log('夜间模式关闭');
        }else if(night == '1'){
        document.querySelector('link[title="dark"]').disabled = true;
        document.querySelector('link[title="dark"]').disabled = false;
        console.log('夜间模式开启');

        }
    }
})();
</script>

建议放在页面底部,我这里用的是Typecho搭建的网站,其它里面有部分PHP代码需要修改一下。

二、CSS代码部分

<link href="<?php $this->options->themeUrl('statics/dark.css'); ?>" rel="<?php if($_COOKIE['night'] != '1'){echo 'alternate ';} ?>stylesheet" type="text/css" title="dark">

在header.php里面加上上面的代码,夜晚模式就让dark.css生效,所以呢,接下来就是在statics文件夹里面创建这个css文件,里面写暗黑模式的相关样式即可。

三、效果演示

可以去我的网站看看效果,在网站右上角有个切换开关,代码如下:

<a href="javascript:switchNightMode()" target="_self" class="darkmode">开启夜间模式</a>
1
Typecho的Joe主题新增cnzz统计
« 上一篇 06-08
Joe主题新增海报功能——配合插件
下一篇 » 06-10

评论 (1)

插入图片
  1. 头像
    11223344 Lv.1   广东省江门市
    Windows 10 · Google Chrome
    沙发

    000000000000000000000w晚上十点

    回复