特性
- 原生JS,不依赖其他框架
- 带Cookie, 刷新保持不变。
- 自己写css
Demo
关键Html
css
header {
background: #999;
margin: 0 auto;
max-width: 1120px;
padding: 20px;
text-align: center;
}
a {
color: #000;
text-decoration: none;
}
.container {
max-width: 1120px;
background: #ececec;
margin: 0 auto;
color: #4e4e4e;
padding: 15px;
}
.night {
background: #333;
}
.night header {
background: #222;
}
.night a {
color: #ffffff;
}
.night .container {
border: 1px solid #444;
background: #3c3c3c;
color: #bfbfbf;
}
Html
<header>
<a href="javascript:switchNightMode()" tar="_self"><i class="fa fa-adjust"></i> 模式切换</a>
</header>
<script type="text/javascript">
<!--//夜间模式cookie-->
(function() {
if (document.cookie.replace(/(?:(?:^|.*;\s*)night\s*\=\s*([^;]*).*$)|^.*$/, "$1") === '') {
//设置开启时间和结束时间
if (new Date().getHours() > 15 || new Date().getHours() < 14) {
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"
console.log(' 夜间模式');
} else {
document.body.classList.remove('night');
document.cookie = "night=0"
console.log(' 白天模式');
}
}
</script>
1 条评论
我怎么就进来了,NICE NICE,统统打包带走,包括博主