网站夜间模式是怎样实现的?
整体思路
夜间模式开关按钮:用来手动切换夜间模式的,会存储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 函数
1 2 3 4 5 6 7 8 9 10 11 12 13 | 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('夜间模式关闭'); } } |
指定时间进入夜间模式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | (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
1 | <link href="dark.css" rel="<?php if($_COOKIE['night'] != '1'){echo 'alternate ';} ?>stylesheet" type="text/css" title="dark"> |
本文已通过「原本」原创作品认证,未经作者授权请勿直接转载,负责将依法追究其法律责任。
如果认为本文对您有所帮助请赞助本站
支付宝扫一扫赞助
微信钱包扫描赞助
赏