最近在逛各个大佬的博客,发现了个很有趣的功能,就是网页中的夜间模式
并且切换到夜间模式,刷新页面并不会恢复
然后自己试着实现这个功能
直接附上代码
代码写的比较糙,需要的小伙伴自行随意修改
测试按钮
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
*{
margin: 0;
padding: 0;
}
body{
transition: all 1s;
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
}
.box{
width: 100%;
height: 100%;
text-align: center;
}
#an{
display: inline-block;
width: 50px;
height: 50px;
cursor: pointer;
border-radius: 10px;
background-size: 100%;
background-repeat: no-repeat;
}
</style>
</head>
<body>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.0/jquery.js"></script>
<script type="text/javascript">
// 声明所用到的变量
var y = parseInt(getCookie("night")),
a = document.getElementsByTagName("a"),
j,
i,
name,
ca,
c;
// 返回cookie指定参数的方法
function getCookie(cname){
name = cname + "=";
ca = document.cookie.split(';');
for(i=0; i<ca.length; i++) {
c = ca[i].trim();
if (c.indexOf(name)==0) return c.substring(name.length,c.length);
}
return "";
}
// 判断cookie值中的night为 0 or 1 ;
function panduan(){
y = parseInt(getCookie("night"));
if(y == 0){ // 白天模式的样式
document.body.style.backgroundColor = "";
document.body.style.color = "";
// $("#an").html("夜间模式"); // 切换按钮 文字 型
$("#an").css("background-image", "url(img/夜晚.png)"); // 切换按钮 图标 型
for(j = 0; j < a.length; j++){
a[j].style.color = ""
}
}else if(y == 1){ // 夜间模式的样式
document.body.style.backgroundColor = "black";
document.body.style.color = "white";
// $("#an").html("白天模式");
$("#an").css("background-image", "url(img/白天.png)");
for(j = 0; j < a.length; j++){
a[j].style.color = "white"
}
}
}
// 判断night是否存在,设置初始cookie值
if(y == 0){
panduan();
}else if(y == 1){
panduan();
}else{ // night不存在则执行,初始化night = 0 即 白天模式
document.cookie="night = 0; expires=Thu, 18 Dec 2043 12:00:00 GMT; path=/";
panduan();
}
// 刷新页面时直接执行判断方法,从而实现刷新页面
panduan();
window.onload = function(){
panduan(); // 页面资源加载完成后,再次执行判断方法(可删)
$("#an").click(function(){
if(y == 0){
document.cookie="night = 1; expires=Thu, 18 Dec 2043 12:00:00 GMT; path=/"; // 修改 1 / 夜间
panduan();
}else if(y == 1){
document.cookie="night = 0; expires=Thu, 18 Dec 2043 12:00:00 GMT; path=/"; // 修改 0 / 白天
panduan();
}else{
document.cookie="night = 1; expires=Thu, 18 Dec 2043 12:00:00 GMT; path=/"; // 第一次加载,设置默认cookie值
panduan();
}
})
}
</script>
<div class="box">
<div id="an"></div>
<div id="">
<a href="">这是a标签</a>
<p>这是p标签</p>
<b>这是b标签</b>
</div>
</div>
</body>
</html>