如何给网站添加主题切换功能?


localStorage.getItem window.matchMedia(“(prefers-color-scheme: dark)“).matches 监听用户点击切换

使用 CSS 变量作为主题

:root {
    --background-color: #fff;
    --text-color: #121416d8;
    --link-color: #543fd7;
}

html[data-theme='light'] {
	color-scheme: light;
    --background-color: #fff;
    --text-color: #121416d8;
    --link-color: #543fd7;
}

html[data-theme='dark'] {
	 color-scheme: dark;
    --background-color: #212a2e;
    --text-color: #F7F8F8;
    --link-color: #828fff;
}

@media (prefers-color-scheme: dark) {
  html:not([data-theme]) {
    color-scheme: dark;
    --color-surface-0: black;
  }
}

JS切换

 // 获取当前主题 
 const theme = (() => {
    if (typeof localStorage !== "undefined" && localStorage.getItem("theme")) {
      return localStorage.getItem("theme");
    }
    if (window.matchMedia("(prefers-color-scheme: dark)").matches) {
      return "dark";
    }
    return "light";
  })();

  if (theme === "light") {
    document.documentElement.classList.remove("dark");
    document.documentElement.setAttribute("data-theme", "light");
  } else {
    document.documentElement.classList.add("dark");
    document.documentElement.setAttribute("data-theme", "dark");
  }
	
  window.localStorage.setItem("theme", theme);

  //   const newTheme = getCachedtheme === "light" ? "dark" : "light";
  const handleToggleClick = () => {
    const element = document.documentElement;
    element.classList.toggle("dark");

    const isDark = element.classList.contains("dark");
    localStorage.setItem("theme", isDark ? "dark" : "light");
    document.documentElement.setAttribute(
      "data-theme",
      isDark ? "dark" : "light"
    );
  };

  document
    .getElementById("themeToggle")
    .addEventListener("click", handleToggleClick);