之前我的另一个网站改过夜间模式,时间太久了重新写出来记录一下。
首先第一步,在您的页面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写到你哭。