因为晚上关灯后看网站的文章确实刺眼,当然也可以调节手机亮度,但确实很少人会在关灯后看手机,对眼睛伤害很大,所以想给博客主题添加夜间模式得功能,本文教你怎么实现。
下面分享两种方法,一种是根据时间自动变换为夜间模式,另一种是按钮切换的方式。
时间调节
首先加入js代码,你可以扔footer页脚:
<script type="text/javascript">
//夜间模式
(function(){
if(document.cookie.replace(/(?:(?:^|.*;\s*)night\s*\=\s*([^;]*).*$)|^.*$/, "$1") === ''){
if(new Date().getHours() > 22 || 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');
}
}
})();
//夜间模式切换
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('夜间模式关闭');
}
}
</script>
其次在header页头的body加入php判断
检测到cookie相关字段直接输出body class为night,防止页面闪烁。
<body class="<?php echo($_COOKIE['night'] == '1' ? 'night' : ''); ?>">
最后调试CSS
body.night xxx ,xxx覆盖替换的css样式,body.night img 是把图片降低亮度,有些地方图片如果没有降低亮度,那么也像前面那样加入。
body.night xxx{
background-color: #263238;
color: #aaa;
}
body.night img {
filter: brightness(30%);
}
我的css修改例子,看一下应该就懂了。
原文链接:https://94wz.top/2334.html,转载请注明出处。


评论0