这个效果还是挺实用的,网页上多数教程用 Cookies 缓存机制实现的,本文略有不同。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>黑夜模式</title>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<style>
/* 白天样式 */
.box {
width: 300px;
height: 300px;
background: orange;
}
/* 黑夜样式 */
html[dark='true'] body {
background: #333;
color: #bbb
}
html[dark='true'] .box {
background: red;
}
#dark {
cursor: pointer
}
</style>
</head>
<body>
<!--darkmode start-->
<div class="box"></div>
<a id="dark" href="javascript:">黑</a>
<!--darkmode end-->
</body>
</html>
<script>
if (localStorage.getItem('dark')) {
$('html').attr('dark', true)
$('#dark').text('白')
} else {
$('html').removeAttr('dark', true)
$('#dark').text('黑')
}
$('#dark').on('click', function () {
if ($('html').attr('dark')) {
$('html').removeAttr('dark')
localStorage.removeItem('dark')
$('#dark').text('黑')
} else {
$('html').attr('dark', true)
localStorage.setItem('dark', true)
$('#dark').text('白')
}
})
</script>
评语 (0)