分享学习记录
互联网技术知识

WordPress添加夜间模式cookie版的教程

将下列代码放入子主题 child.js 文件中

    //夜间模式
(function(){
    if(document.cookie.replace(/(?:(?:^|.*;\s*)night\s*\=\s*([^;]*).*$)|^.*$/, "$1") === ''){
        if(new Date().getHours() > 22 || new Date().getHours() < 6){
            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*)night\s*\=\s*([^;]*).*$)|^.*$/, "$1") || '0';
        if(night == '0'){
            document.body.classList.remove('night');
        }else if(night == '1'){
            document.body.classList.add('night');
        }
    }
})();
//夜间模式切换
function switchNightMode(){
    var night = document.cookie.replace(/(?:(?:^|.*;\s*)night\s*\=\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('夜间模式关闭');
    }
}

将下列代码加入到 主题或子主题 header.php 文件中

具体位置大概在17行后

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

将下列代码放入想要展示的地方即可调用切换开关

<a href="javascript:switchNightMode()" target="_self">查看效果</a>
赞(15)
文章名称:《WordPress添加夜间模式cookie版的教程》
文章链接:https://www.bailuze.com/1010.html
本站所有文章,如无特殊说明或标注,均为本站原创发布。任何在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。
本站专注于百度、搜狗、360、谷歌、bing等常见搜索引擎的优化,关键词排名的提高,诚意咨询邮箱526009505@qq.com
分享到