js夜间实现
夜间模式实现方法
通过JavaScript实现夜间模式通常涉及修改页面样式或切换CSS类。以下是几种常见方法:
CSS变量切换
function toggleNightMode() {
document.documentElement.style.setProperty('--bg-color', isNightMode ? '#ffffff' : '#1a1a1a');
document.documentElement.style.setProperty('--text-color', isNightMode ? '#333333' : '#e0e0e0');
}
类名切换
const body = document.body;
function toggleDarkMode() {
body.classList.toggle('dark-mode');
}
// CSS示例
.dark-mode {
background-color: #121212;
color: #f5f5f5;
}
使用媒体查询同步

const darkModeMediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
darkModeMediaQuery.addListener((e) => {
document.body.classList.toggle('dark-mode', e.matches);
});
持久化存储方案
使用localStorage保存用户偏好:
function setDarkMode(isDark) {
localStorage.setItem('darkMode', isDark);
document.body.classList.toggle('dark-mode', isDark);
}
// 初始化时读取
const savedMode = localStorage.getItem('darkMode');
if (savedMode !== null) {
document.body.classList.toggle('dark-mode', savedMode === 'true');
}
渐变过渡效果
添加CSS过渡使切换更平滑:

body {
transition: background-color 0.3s ease, color 0.3s ease;
}
完整实现示例
HTML结构:
<button id="themeToggle">切换夜间模式</button>
JavaScript实现:
const themeToggle = document.getElementById('themeToggle');
const prefersDarkScheme = window.matchMedia('(prefers-color-scheme: dark)');
const currentTheme = localStorage.getItem('theme');
if (currentTheme === 'dark' || (!currentTheme && prefersDarkScheme.matches)) {
document.body.classList.add('dark-theme');
}
themeToggle.addEventListener('click', () => {
document.body.classList.toggle('dark-theme');
const theme = document.body.classList.contains('dark-theme') ? 'dark' : 'light';
localStorage.setItem('theme', theme);
});
CSS样式:
:root {
--bg-light: #ffffff;
--text-light: #333333;
--bg-dark: #1a1a1a;
--text-dark: #e0e0e0;
}
body {
background-color: var(--bg-light);
color: var(--text-light);
transition: all 0.3s ease;
}
body.dark-theme {
background-color: var(--bg-dark);
color: var(--text-dark);
}






