整体流程
夜间模式开关按钮:用来手动切换夜间模式的,会存储cookie。
自动夜间模式:当cookie为空时,浏览器时间大于22点小于6点时会自动进入夜间模式,并存储cookie。
后端配合:php判断是否有cookie,有的话直接输出夜间css,避免切换页面时网页闪烁。
具体操作
引入黑夜 css
<link href="dark.css" rel="alternate stylesheet" type="text/css" title="dark">
有title
熟悉rel属性值同时包含alternate stylesheet
的<link>
作为备选样式CSS文件加载,默认不渲染。
切换夜间模式的 js 函数
function switchNightMode(){
var night = document.cookie.replace(/(?:(?:^|.*;\s*)night\s*\=\s*([^;]*).*$)|^.*$/, "$1") || '0';
if(night == '0'){
document.querySelector('link[title="dark"]').disabled = true;
document.querySelector('link[title="dark"]').disabled = false;
document.cookie = "night=1;path=/"
console.log('夜间模式开启');
}else{
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() > 22 || new Date().getHours() < 6){
document.querySelector('link[title="dark"]').disabled = true;
document.querySelector('link[title="dark"]').disabled = false;
document.cookie = "night=1;path=/"
console.log('夜间模式开启');
}else{
document.cookie = "night=0;path=/"
console.log('夜间模式关闭');
}
}else{
var night = document.cookie.replace(/(?:(?:^|.*;\s*)night\s*\=\s*([^;]*).*$)|^.*$/, "$1") || '0';
if(night == '0'){
document.querySelector('link[title="dark"]').disabled = true;
console.log('夜间模式关闭');
}else if(night == '1'){
document.querySelector('link[title="dark"]').disabled = true;
document.querySelector('link[title="dark"]').disabled = false;
console.log('夜间模式开启');
}
}
})();
php 后端判断 cookie 进行加载 css
<link href="dark.css" rel="<?php if($_COOKIE['night'] != '1'){echo 'alternate ';} ?>stylesheet" type="text/css" title="dark">
适配 Mac 的 Dark Mode
纯js判断设备是否进入了夜间模式,感谢simplify
提供代码
if (
window.matchMedia &&
window.matchMedia("(prefers-color-scheme: dark)").matches
) {
alert('进入夜间模式');
}
旧版适配 Mac 的 Dark Mode的方案
需要插入段css然后用js判断css的变化,来监控是否进入夜间模式
插入 css
html {
content: "";
}
/* Light mode */
@media (prefers-color-scheme: light) {
html {
content: "light";
}
}
/* Dark mode */
@media (prefers-color-scheme: dark) {
html {
content: "dark";
}
}
前端使用 JS 检查
const mode = getComputedStyle(document.documentElement).getPropertyValue('content');
if(mode == '"dark"'){alert('进入夜间模式');}
最后
在dark.css
里重写一些元素的背景色文字色等等。
参考
1,link rel=alternate网站换肤功能最佳实现
2,给博客添加夜间模式
3,prefers-color-scheme: CSS Media Query
版权属于:泽泽社长
本文链接:https://blog.zezeshe.com/archives/night-mode-of-website.html
本站未注明转载的文章均为原创,并采用
CC BY-NC-SA 4.0 授权协议,转载请注明来源,谢谢!
可以折腾折腾
夜间测css怎么调都感觉不太好看
折腾ok了,我主题比较简单,css随便调一下就看着还可以2333
qq爹.我来看你了
欢迎欢迎,感觉自己博客快凉了
不都一样 我博客都快落灰了
告诉你个简易的css夜间模式,css3的反色滤镜,对整个页面进行反色,然后对照片重复反色还原为原色。
滤镜兼容不太好,尤其是手机端,所以还是传统点的操作靠谱