diff --git a/static/js/theme.js b/static/js/theme.js new file mode 100644 index 0000000..3113231 --- /dev/null +++ b/static/js/theme.js @@ -0,0 +1,36 @@ +(function () { + var KEY = 'qihuo-theme'; + + function apply(theme) { + document.documentElement.setAttribute('data-theme', theme); + try { + localStorage.setItem(KEY, theme); + } catch (e) { /* ignore */ } + var btn = document.getElementById('theme-toggle'); + if (btn) { + btn.setAttribute('data-active', theme); + btn.setAttribute('aria-label', theme === 'light' ? '切换到深色' : '切换到浅色'); + } + } + + var saved = null; + try { + saved = localStorage.getItem(KEY); + } catch (e) { /* ignore */ } + + if (saved === 'light' || saved === 'dark') { + apply(saved); + } else { + var prefersLight = window.matchMedia && window.matchMedia('(prefers-color-scheme: light)').matches; + apply(prefersLight ? 'light' : 'dark'); + } + + document.addEventListener('DOMContentLoaded', function () { + var btn = document.getElementById('theme-toggle'); + if (!btn) return; + btn.addEventListener('click', function () { + var cur = document.documentElement.getAttribute('data-theme') || 'dark'; + apply(cur === 'dark' ? 'light' : 'dark'); + }); + }); +})(); diff --git a/templates/base.html b/templates/base.html index 5b1193d..6fd31e2 100644 --- a/templates/base.html +++ b/templates/base.html @@ -4,24 +4,178 @@