100字范文,内容丰富有趣,生活中的好帮手!
100字范文 > html实现网页夜间模式 通过JS和PHP实现网站夜间模式的自动切换

html实现网页夜间模式 通过JS和PHP实现网站夜间模式的自动切换

时间:2024-07-20 23:22:29

相关推荐

html实现网页夜间模式 通过JS和PHP实现网站夜间模式的自动切换

前言

想做夜间模式很久了,只是苦于JS小白,不会操作Cookie,最近看到QQ爹的《网站夜间模式的实现》

这个功能主要包括三个部分夜间模式开关按钮:用来手动切换夜间模式的,自动存储显示模式 Cookie。

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

后端处理:PHP判断是否有显示模式 Cookie,有的话直接输出夜间 class,避免进入时网页闪烁。

具体操作

自动根据时间输出夜间模式类名

引入夜间模式CSS

可以在原来的style.css里新增样式就行.dark {

background-color: #333;

color: #eee;

}

.dark a:color {

color: #fafafa;

}

...

只要是夜间模式的CSS,增加.dark选择器

指定时间进入夜间模式

JS代码来自QQ爹function autoNightMode() {

if (document.cookie.replace(/(?:(?:^|.*;\s*)nightMode\s*\=\s*([^;]*).*$)|^.*$/, "$1") === '') {

if (new Date().getHours() >= 22 || new Date().getHours() < 6) {

$('body').addClass('dark');

document.cookie = "nightMode=1;path=/"

console.log('夜间模式开启');

} else {

$('body').removeClass('dark');

document.cookie = "nightMode=0;path=/"

console.log('夜间模式关闭');

}

} else {

var night = document.cookie.replace(/(?:(?:^|.*;\s*)nightMode\s*\=\s*([^;]*).*$)|^.*$/, "$1") || '0';

if (night == '0') {

console.log('夜间模式关闭');

} else if (night == '1') {

$('body').addClass('dark');

console.log('夜间模式开启');

}

}

}

autoNightMode();

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。