`export function setStyle(type) {
const lightUrl = 'https://cdn.jsdelivr.net/gh/highlightjs/cdn-release@11.9.0/build/styles/github.min.css';
const darkUrl = 'https://cdn.jsdelivr.net/gh/highlightjs/cdn-release@11.9.0/build/styles/github-dark.min.css';
const highlightJsLink = document.querySelector('link[href*="highlightjs"]');
const preferDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
const initialType = type === 'auto' ? (preferDark ? 'night' : 'day') : type;
if (initialType === 'night') {
if (highlightJsLink) {
highlightJsLink.href = darkUrl;
}
}
const light = document.querySelector('link.nightmode-light[rel=stylesheet]');
const dark = document.querySelector('link.nightmode-dark[rel=stylesheet]');
const url = getUrls()[type];
if (light && dark) {
// 如果存在 light 和 dark 两种样式表,则替换为新的样式表
highlightJsLink.href = darkUrl; // 切换到暗色模式的 highlight.js 样式表
const newLink = document.createElement('link');
newLink.rel = 'stylesheet';
newLink.className = 'nightmode';
newLink.href = url;
// 根据浏览器支持情况进行样式表加载处理
if ('onload' in newLink) {
newLink.onload = function () {
light.remove();
dark.remove();
};
} else {
light.remove();
dark.remove();
}
document.head.append(newLink);
} else {
// 如果只存在单一的样式表,则更新其 href 属性即可
const el = light || dark || document.querySelector('link.nightmode[rel=stylesheet]');
if (url !== el.href) {
el.href = url;
el.className = 'nightmode';
highlightJsLink.href = type === 'night' ? darkUrl : lightUrl; // 根据模式切换到对应的 highlight.js 样式表
}
}
const colorScheme = document.querySelector('meta[name="color-scheme"]');
if (colorScheme) {
colorScheme.content = type === 'night' ? 'dark' : 'light';
}
// 触发自定义事件
const event = new CustomEvent('fofnightmodechange', { detail: type });
document.dispatchEvent(event);
}`