js实现开灯
使用HTML和JavaScript实现开关灯效果
通过修改网页背景色和文字颜色模拟开灯/关灯效果。以下是一个简单实现方案:
<!DOCTYPE html>
<html>
<head>
<title>灯光控制</title>
<style>
body {
transition: background-color 0.5s ease;
}
.dark {
background-color: #333;
color: white;
}
.light {
background-color: white;
color: black;
}
</style>
</head>
<body class="light">
<button onclick="toggleLight()">开关灯</button>
<script>
function toggleLight() {
const body = document.body;
if (body.classList.contains('light')) {
body.classList.remove('light');
body.classList.add('dark');
} else {
body.classList.remove('dark');
body.classList.add('light');
}
}
</script>
</body>
</html>
使用CSS变量实现主题切换
更灵活的实现方式,通过CSS变量控制颜色主题:
document.addEventListener('DOMContentLoaded', () => {
const toggleBtn = document.getElementById('theme-toggle');
const root = document.documentElement;
toggleBtn.addEventListener('click', () => {
const currentTheme = root.getAttribute('data-theme');
if (currentTheme === 'dark') {
root.setAttribute('data-theme', 'light');
} else {
root.setAttribute('data-theme', 'dark');
}
});
});
对应的CSS部分:
:root {
--bg-color: #ffffff;
--text-color: #000000;
}
[data-theme="dark"] {
--bg-color: #222222;
--text-color: #ffffff;
}
body {
background-color: var(--bg-color);
color: var(--text-color);
transition: all 0.3s ease;
}
使用localStorage保存用户偏好
增强用户体验,记住用户选择的主题:
function toggleTheme() {
const root = document.documentElement;
const currentTheme = localStorage.getItem('theme') || 'light';
const newTheme = currentTheme === 'light' ? 'dark' : 'light';
root.setAttribute('data-theme', newTheme);
localStorage.setItem('theme', newTheme);
}
// 初始化时读取保存的主题
function initTheme() {
const savedTheme = localStorage.getItem('theme') || 'light';
document.documentElement.setAttribute('data-theme', savedTheme);
}
window.addEventListener('DOMContentLoaded', initTheme);
使用classList.toggle简化代码
更简洁的切换实现方式:
const themeBtn = document.querySelector('.theme-toggle');
themeBtn.addEventListener('click', () => {
document.body.classList.toggle('dark-mode');
});
对应的CSS:

body.dark-mode {
background-color: #1a1a1a;
color: #f0f0f0;
}
这些方法都可以实现基本的"开灯/关灯"效果,区别在于实现细节和扩展性。第一种方法最简单直接,后续方法提供了更好的可维护性和用户体验。






