html 黑夜模式,网站夜间模式的实现

整体流程

夜间模式开关按钮:用来手动切换夜间模式的,会存储cookie。

自动夜间模式:当cookie为空时,浏览器时间大于22点小于6点时会自动进入夜间模式,并存储cookie。

后端配合:php判断是否有cookie,有的话直接输出夜间css,避免切换页面时网页闪烁。

具体操作

引入黑夜 css

有title熟悉rel属性值同时包含alternate stylesheet的作为备选样式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

适配 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

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值