main
xgkblog/assets/js/main.js
main.js2.4 KB
 document.addEventListener('DOMContentLoaded', function() {
    // 把您所有的菜单、搜索和暗黑模式逻辑放在这里

         
   // 1. 汉堡菜单逻辑
const menuToggle = document.getElementById('menuToggle');
const navMenu = document.getElementById('navMenu');

menuToggle.addEventListener('click', () => {
    menuToggle.classList.toggle('active');
    navMenu.classList.toggle('mobile-active');
});

// 2. 搜索弹窗逻辑
const searchOverlay = document.getElementById('searchOverlay');
const searchInput = document.getElementById('searchInput');

document.getElementById('openSearch').addEventListener('click', () => {
    searchOverlay.classList.add('active');
    searchInput.focus();
});

searchOverlay.addEventListener('click', (e) => {
    if (e.target === searchOverlay) searchOverlay.classList.remove('active');
});

document.addEventListener('keydown', (e) => {
    if (e.key === 'Escape') searchOverlay.classList.remove('active');
});

// 3. 暗黑模式逻辑 (带 Cookie 记忆与图标切换)
const themeToggle = document.getElementById('themeToggle');
const body = document.body;

// SVG 图标常量
const moonIcon = '<svg viewBox="0 0 24 24"><path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"></path></svg>';
const sunIcon = '<svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="5"></circle><line x1="12" y1="1" x2="12" y2="3"></line><line x1="12" y1="21" x2="12" y2="23"></line><line x1="4.22" y1="4.22" x2="5.64" y2="5.64"></line><line x1="18.36" y1="18.36" x2="19.78" y2="19.78"></line><line x1="1" y1="12" x2="3" y2="12"></line><line x1="21" y1="12" x2="23" y2="12"></line><line x1="4.22" y1="19.78" x2="5.64" y2="18.36"></line><line x1="18.36" y1="5.64" x2="19.78" y2="4.22"></line></svg>';

// 页面加载时检查 Cookie,恢复主题状态
if (document.cookie.includes('theme=dark')) {
    body.classList.add('dark-mode');
    themeToggle.innerHTML = sunIcon; // 暗黑模式下显示太阳图标
}

themeToggle.addEventListener('click', () => {
    body.classList.toggle('dark-mode');
    const isDark = body.classList.contains('dark-mode');
    
    // 动态切换 SVG 图标
    themeToggle.innerHTML = isDark ? sunIcon : moonIcon;
    
    // 将主题偏好存入 Cookie (有效期 30 天)
    const expires = new Date(Date.now() + 30 * 24 * 60 * 60 * 1000).toUTCString();
    document.cookie = `theme=${isDark ? 'dark' : 'light'}; expires=${expires}; path=/`;
});


});