5 lines
1012 B
JavaScript
5 lines
1012 B
JavaScript
|
function getTheme(){return localStorage.getItem('theme')?localStorage.getItem('theme'):null;}
|
||
|
function setTheme(style){document.documentElement.setAttribute('data-theme',style);localStorage.setItem('theme',style);}
|
||
|
function init(){const theme=getTheme();const userPrefersDark=window.matchMedia&&window.matchMedia('(prefers-color-scheme: dark)').matches;if(theme===null){if(userPrefersDark){setTheme('dark');}else if(!document.documentElement.getAttribute('data-theme')){setTheme('light');}else{setTheme(document.documentElement.getAttribute('data-theme'));}}else{if(theme==='light'){document.documentElement.setAttribute('data-theme','light');}else{document.documentElement.setAttribute('data-theme','dark');}}}
|
||
|
function switchTheme(){const theme=getTheme();if(theme==='light'){setTheme('dark');}else{setTheme('light');}}
|
||
|
document.addEventListener('DOMContentLoaded',function(){const themeSwitcher=document.querySelector('.theme-switch');themeSwitcher.addEventListener('click',switchTheme,false);},false);init();
|