这篇文章将解释如何为网站启用/禁用浅色和深色模式。此外,你还将学习如何自定义整个网站的配色方案。
启用/禁用浅色和深色模式
AstroPaper 主题默认包含浅色和深色模式。换句话说,会有两种配色方案,一种用于浅色模式,另一种用于深色模式。此默认行为可以在 SITE 配置对象中禁用。
export const SITE = {
website: "https://blog.liorawild.com/", // 将其替换为你部署的域名
author: "Sat Naing",
profile: "https://satnaing.dev/",
desc: "A minimal, responsive and SEO-friendly Astro blog theme.",
title: "AstroPaper",
ogImage: "astropaper-og.jpg",
lightAndDarkMode: true,
postPerIndex: 4,
postPerPage: 4,
scheduledPostMargin: 15 * 60 * 1000, // 15 minutes
showArchives: true,
showBackButton: true, // 在帖子详情中显示返回按钮
editPost: {
enabled: true,
text: "Suggest Changes",
url: "https://github.com/satnaing/astro-paper/edit/main/",
},
dynamicOgImage: true,
lang: "en", // html 语言代码。将其设置为空,默认将为 "en"
timezone: "Asia/Bangkok", // 默认全球时区 (IANA 格式) https://en.wikipedia.org/wiki/List_of_tz_database_time_zones
} as const;src/config.ts
要禁用 light & dark mode(浅色和深色模式),请将 SITE.lightAndDarkMode 设置为 false。
选择初始配色方案
默认情况下,如果我们禁用 SITE.lightAndDarkMode,我们将只能获得系统首选的颜色方案(prefers-color-scheme)。
因此,要选择初始配色方案而不是使用系统首选项,我们必须在 theme.ts 中的 initialColorScheme 变量中设置配色方案。
// 初始配色方案
// 可以是 "light"、"dark" 或空字符串(表示系统首选颜色方案)
const initialColorScheme = ""; // "light" | "dark"
function getPreferTheme(): string {
// 从本地存储获取主题数据(用户的显式选择)
const currentTheme = localStorage.getItem("theme");
if (currentTheme) return currentTheme;
// 如果设置了初始配色方案,则返回它(站点默认值)
if (initialColorScheme) return initialColorScheme;
// 返回用户设备的首选颜色方案(系统回退)
return window.matchMedia("(prefers-color-scheme: dark)").matches
? "dark"
: "light";
}
// ...src/scripts/theme.ts
initialColorScheme 变量可以保存两个值:"light"、"dark"。如果你不想指定初始配色方案,可以保留空字符串(默认)。
""- 系统首选颜色方案。(默认)"light"- 使用浅色模式作为初始配色方案。"dark"- 使用深色模式作为初始配色方案。
为什么 initialColorScheme 不在 config.ts 中?
为了避免页面重新加载时出现颜色闪烁,我们必须在页面加载时尽早放置主题初始化 JavaScript 代码。主题脚本分为两部分:`` 中的最小内联脚本立即设置主题,以及异步加载的完整脚本。这种方法可以防止 FOUC(无样式内容闪烁),同时保持最佳性能。自定义配色方案
AstroPaper 主题的浅色和深色配色方案都可以在 global.css 文件中自定义。
@import "tailwindcss";
@import "./typography.css";
@custom-variant dark (&:where([data-theme=dark], [data-theme=dark] *));
:root,
html[data-theme="light"] {
--background: #fdfdfd;
--foreground: #282728;
--accent: #006cac;
--muted: #e6e6e6;
--border: #ece9e9;
}
html[data-theme="dark"] {
--background: #212737;
--foreground: #eaedf3;
--accent: #ff6b01;
--muted: #343f60bf;
--border: #ab4b08;
}
/* ... */src/styles/global.css
在 AstroPaper 主题中,:root 和 html[data-theme="light"] 选择器定义浅色配色方案,而 html[data-theme="dark"] 定义深色配色方案。
要自定义你自己的配色方案,请在 :root, html[data-theme="light"] 中指定浅色颜色,在 html[data-theme="dark"] 中指定深色颜色。
以下是颜色属性的详细解释。
| 颜色属性 | 定义与用法 |
|---|---|
--background | 网站的主色调。通常是主要背景。 |
--foreground | 网站的次要颜色。通常是文本颜色。 |
--accent | 网站的强调色。链接颜色、悬停颜色等。 |
--muted | 悬停状态等的卡片和滚动条背景颜色。 |
--border | 边框颜色。用于边框工具类和视觉分隔。 |
这是更改浅色配色方案的示例。
/* ... */
:root,
html[data-theme="light"] {
--background: #f6eee1;
--foreground: #012c56;
--accent: #e14a39;
--muted: #efd8b0;
--border: #dc9891;
}
/* ... */src/styles/global.css
查看 AstroPaper 已经为你制作的一些预定义配色方案。