胖蒜

分享有价值的资源

js + css 自动/手工开启网站白天/黑夜模式

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

一、JS部分代码

<script type = "text/javascript" >
function switchNightMode(){
    var night = document.cookie.replace(/(?:(?:^|.*;\s*)night\s*\=\s*([^;]*).*$)|^.*$/, "$1") || '0';
    if(night == '0'){
        document.body.classList.add("night");
        document.querySelector('link[title="dark"]').disabled = false;
        document.cookie = "night=1;path=/"
        console.log('夜间模式开启');
    }else{
        document.body.classList.remove("night");
        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() > 19 || new Date().getHours() < 6){
            document.body.classList.add("night");
            document.querySelector('link[title="dark"]').disabled = false;
            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*)night\s*\=\s*([^;]*).*$)|^.*$/, "$1") || '0';
        if(night == '0'){
            document.body.classList.remove("night");
            document.querySelector('link[title="dark"]').disabled = true;
            console.log('夜间模式关闭');
        }else if(night == '1'){
            document.body.classList.add("night");
            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文件,里面写暗黑模式的相关样式即可。

三、PHP代码部分

在body里面加个cookie,代码如下:
<?php echo($_COOKIE['night'] == '1' ? 'night' : ''); ?>

四、效果演示

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

<a href="javascript:switchNightMode()" target="_self" class="darkmode">开启夜间模式</a>

演示地址:https://pangsuan.com/

白天模式效果图:
白天模式.png

夜间模式效果图:
夜晚模式.png

还马马虎虎对吧,夜间模式的CSS可能还得调一下更好。

感觉很棒,欢迎点赞 OR 打赏~

分享到:

评论 (5)

立即登录评论
可联系QQ744272645咨询

    666

    ᝰꫛꫀꪝ

    可以强大

    ᝰꫛꫀꪝ
马上咨询 自媒体号