网站添加暗黑模式html+js

有些时候我们喜欢大半夜不睡觉刷抖音刷微博,突发奇想为什么我们不能让网站在夜间的时候自动打开夜间模式,让网页背景变暗,让图片变暗,这样那些夜猫观看我们的博客时候就不会那么刺眼啦,哈哈。话不多说,上教程!

首先第一步,在您的页面footer文件加入以下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.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*)night\s*\=\s*([^;]*).*$)|^.*$/, "$1") === "") {
        if (new Date().getHours() > 21 || 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")
            }
        }
    }
})();
</script>

加好后在您的页面body处加入php判断,这样当检测到cookie相关字段时直接输出body的class为night,已防止页面闪烁。

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

最后再将网站中所有需要变暗的地方调整其css,已达到变暗效果,具体css调整示例可看下方

body.night 需要调整的区块{
    background-color: #000000;
    color: #aaa;
}
body.night img {
    filter: brightness(30%);
}

这样当晚上9点到白天6点之间,网站打开时就自动会变成暗黑模式。当然,你也可以加一个按钮,来手动控制打开关闭暗黑模式。如下代码

<a href="javascript:switchNightMode()" target="_self">Dark</a>

至此教程就结束了,需要强调的是,该方法需要修改的css非常的多,需要大家细心的调整及适配,不太建议过于复杂的网站添加此功能,不然css写到你哭,哈哈!

文章由官网发布,如若转载,请注明出处:https://www.veimoz.com/95
1 条评论
3.8k

发表评论

仅有一条评论

  1. 佛系软件     Win 10 /    Chrome
    2020-11-09 14:47

    可以根据操作系统变换颜色吗

!