EveSunMaple / Frosti

A clean, elegant, and fast static blog template! 🚀 Developed with Astro
https://frosti.saroprock.com
GNU General Public License v3.0
181 stars 30 forks source link

Auto theme #44

Closed Loping151 closed 1 day ago

Loping151 commented 1 month ago

根据时间自动切换主题。我简单写了一下。但是问题是我没想好具体的逻辑怎么写。原来的逻辑是默认白色然后永远继承之前的。下面的版本是加载的时候根据时间决定,然后如果在晚上换回白色,只要重新刷新就回到黑色了。或者只允许无cache的时候根据时间决定。

再或者只允许白色切换为黑色,不允许反过来。~因为夜猫子是真的怕晚上亮瞎~

再再或者就只是给需要的人参考参考。。总之先放这

src/components/ThemeIcon.astro, line85

    const syncThemeToggle = () => {
      const currentTheme = localStorage.getItem("theme");
      if (themeLabel1 && themeLabel2 && themeToggle1 && themeToggle2) {
        const isDark = currentTheme === "dracula";
        themeLabel1.classList.toggle("active", isDark);
        themeLabel2.classList.toggle("active", !isDark);
        themeToggle1.checked = isDark;
        themeToggle2.checked = isDark;
      }
    };

    const autoSetThemeBasedOnTime = () => {
      const hour = new Date().getHours();
      // const currentTheme = localStorage.getItem("theme");
      // if (!currentTheme) {
        if (hour >= 6 && hour < 18) {
          setTheme("winter");
        } else {
          setTheme("dracula");
        }
      // }
    };

    autoSetThemeBasedOnTime();
    syncThemeToggle();