首页 » 收集 » 正文内容
js + css 自动/手工开启网站白天/黑夜模式
寻梦xunm| 735| 收集
3年前
超过1174天 温馨提示
本文最后更新于2021年07月03日,已超过1174天没有更新,若内容或图片失效,请留言反馈。

我采用的是最普通的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>
0 赞 or 打赏
喜欢就打赏一点
微信 支付宝
隐私
Q Q:1340326824
邮箱:vipshiyi@qq.com
QQ群:422720328

我的音乐

微博客-专为自己编写开发的源码