function enableSS(sheetid, enabled) { document.getElementById(sheetid).disabled = !enabled; } <form> <input type="checkbox" onclick="enableSS('ss0', this.checked)">style0<br> <input type="checkbox" onclick="enableSS('ss1', this.checked)">style1<br> <input type="checkbox" onclick="enableSS('ss2', this.checked)">style2<br> </form> <link id="ss0" rel="stylesheet" href="/css/style0.css"> <link id="ss1" rel="stylesheet" href="/css/style1.css"> <link id="ss2" rel="stylesheet" href="/css/style2.css"> 

How can I make the css switch not by input , but by the list li or at least a link. Ie which one pressed that style file and loaded.

Like so

 <ul class="colors"> <li>style0</li> <li>style1</li> <li>style2</li> </ul> 

    1 answer 1

    The load event tracks when the page is loaded, you can start loading the desired style earlier, which we will take from localStorage

     // Сохранение темы в localStorage const saveCssTheme = function (theme) { localStorage.cssTheme = theme; } // Получение темы из localStorage, либо дефолтной const getCssTheme = function () { return localStorage.cssTheme || 'default-theme'; } // Загрузка css файла const loadCssTheme = function (theme) { const link = document.createElement('link'); link.id = theme; link.type = "text/css"; link.rel = 'stylesheet'; link.href = `/css/${theme}.css`; // если мы уже загрузили стили, то не нужно делать это еще раз if(document.getElementById(theme)) return; document.head.appendChild(link); } // Установка темы const setCssTheme = function(theme) { loadCssTheme(theme); saveCssTheme(theme); document.body.setAttribute('class', theme); } // Использование при загрузке страницы document.addEventListener("load", function () { const theme = getCssTheme(); setCssTheme(theme); }); 

    In css let the default be the default theme, the rest will look like this

     body.theme a {} // стиль примениться к элементу a, только если у body есть класс theme body.theme h1 {} 

    UPD
    Buttons to turn on

     <ul class="colors"> <li onclick="setCssTheme('theme0')">style0</li> <li onclick="setCssTheme('theme1')">style1</li> <li onclick="setCssTheme('theme2')">style2</li> </ul> 

    UPD
    The class for body necessary so that css-themes do not overlap each other, if you manage without it, just delete the corresponding code

    If the initial download does not work, try this:

     document.onload = function () { const theme = getCssTheme(); setCssTheme(theme); }; 

    Or in the question add, then use my code

    • This is not enough for me, I need style files and with preservation. - steep
    • @steep, what does saving mean? - ThisMan
    • when navigating through the pages so that the selected style is saved - steep
    • Did not understand about this body.theme a{} - steep
    • And what buttons to turn on? - steep