按钮创建

/blog/_config.stellar.yml

1
2
3
4
5
footer:
social:
mode:
icon: '<svg class="mode-toggle-icon" aria-hidden="true" viewBox="0 0 512 512" height="1em" width="1em" style="transition: transform 0.3s ease; vertical-align: -0.125em;"><path fill="currentColor" d="M448 256c0-106-86-192-192-192V448c106 0 192-86 192-192zM0 256a256 256 0 1 1 512 0A256 256 0 1 1 0 256z"/></svg>'
url: 'javascript:void(0);'

js编写

pjax与暗色模式合并为一个js文件,减少引入文件数

/blog/source/js/app.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
document.addEventListener('DOMContentLoaded', function() {

// 初始化 PJAX
if (typeof Pjax === 'function') {
new Pjax({
selectors: ["head title", "meta[name=description]", ".l_main", ".l_right", "script[data-pjax]"],
cacheBust: false,
analytics: false
});
}
initEverything();

// PJAX 跳转后,重新初始化
document.addEventListener('pjax:complete', function () {
// 重载 Stellar 自带功能
if (window.lazyload) window.lazyload();
const codes = document.querySelectorAll('pre code');
if (codes.length > 0 && window.hljs) codes.forEach(block => window.hljs.highlightBlock(block));

initEverything();
});
});

// === 核心初始化函数 ===
function initEverything() {
// 修正图标状态 (让图标显示为当前的月亮或太阳状态)
const currentTheme = document.documentElement.getAttribute('data-theme');
updateIcon(currentTheme === 'dark');

// 绑定切换按钮点击事件
// 找到所有 href 为 javascript:void(0); 的链接(我们在配置文件里设的)
const toggleBtns = document.querySelectorAll('a[href="javascript:void(0);"]');
toggleBtns.forEach(btn => {
btn.removeEventListener('click', handleThemeToggle);
btn.addEventListener('click', handleThemeToggle);
});

}

// 处理点击
function handleThemeToggle(e) {
e.preventDefault();
const isDark = document.documentElement.getAttribute('data-theme') === 'dark';
setTheme(isDark ? 'light' : 'dark');
}

// 设置模式
function setTheme(mode) {
document.documentElement.setAttribute('data-theme', mode);
window.localStorage.setItem('Theme_Mode', mode);
updateIcon(mode === 'dark');
}

function updateIcon(isDark) {
const svgs = document.querySelectorAll('.mode-toggle-icon');
svgs.forEach(svg => {
if (isDark) {
svg.style.transform = 'rotate(180deg)';
svg.style.fill = '#f1c40f';
} else {
svg.style.transform = 'rotate(0deg)';
svg.style.fill = 'currentColor';
}
});
}

js引入

/blog/_config.yml

1
2
3
4
5
6
7
inject:
head:
# --- 防闪白脚本 ---
- '<script>(function(){var s=window.localStorage.getItem("Theme_Mode"),m=window.matchMedia("(prefers-color-scheme:dark)").matches;if(s==="dark"||(!s&&m)){document.documentElement.setAttribute("data-theme","dark")}else{document.documentElement.setAttribute("data-theme","light")}})();</script>'
script:
- <script src="https://cdn.jsdelivr.net/npm/pjax@VERSION/pjax.min.js" defer></script>
- <script src="/js/app.js" defer></script>

本站由 ZBound 使用 Stellar 1.33.1 主题创建。
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处。