js实现关灯
使用JavaScript实现关灯效果
通过修改网页背景色和文字颜色实现关灯效果。以下是几种实现方式:
基础实现方式
创建一个切换按钮控制页面明暗状态:
let isDark = false;
function toggleLights() {
isDark = !isDark;
document.body.style.backgroundColor = isDark ? '#222' : '#fff';
document.body.style.color = isDark ? '#eee' : '#000';
}
添加CSS类切换方式
更推荐使用CSS类切换方式,便于维护:

.dark-mode {
background-color: #222;
color: #eee;
}
function toggleLights() {
document.body.classList.toggle('dark-mode');
}
使用localStorage保存状态
添加状态持久化功能:
function toggleLights() {
document.body.classList.toggle('dark-mode');
const isDark = document.body.classList.contains('dark-mode');
localStorage.setItem('darkMode', isDark);
}
// 页面加载时检查保存的状态
if (localStorage.getItem('darkMode') === 'true') {
document.body.classList.add('dark-mode');
}
完整实现示例
HTML部分:

<button id="lightSwitch">关灯</button>
JavaScript部分:
const switchBtn = document.getElementById('lightSwitch');
function updateButtonText() {
switchBtn.textContent = document.body.classList.contains('dark-mode')
? '开灯'
: '关灯';
}
switchBtn.addEventListener('click', () => {
document.body.classList.toggle('dark-mode');
localStorage.setItem('darkMode', document.body.classList.contains('dark-mode'));
updateButtonText();
});
// 初始化
if (localStorage.getItem('darkMode') === 'true') {
document.body.classList.add('dark-mode');
}
updateButtonText();
进阶方案:匹配系统主题
检测用户系统颜色偏好:
const prefersDark = window.matchMedia('(prefers-color-scheme: dark)');
function applyTheme() {
const isDark = localStorage.getItem('darkMode') === 'true' ||
(localStorage.getItem('darkMode') === null && prefersDark.matches);
document.body.classList.toggle('dark-mode', isDark);
updateButtonText();
}
prefersDark.addEventListener('change', applyTheme);
这些方法提供了从简单到完整的关灯效果实现方案,可根据实际需求选择适合的方式。






