简体   繁体   English

需要帮助使 CSS 文件在 Javascript 中持久化

[英]Need help making CSS file persistent in Javascript

I have an HTML page with two CSS files, one for a light theme and one for a dark theme.我有一个带有两个 CSS 文件的 HTML 页面,一个用于浅色主题,一个用于深色主题。 When I click the respective button, the theme changes to either light.css or dark.css.当我单击相应的按钮时,主题将更改为 light.css 或 dark.css。

However, if I reload the site, it goes back to the light theme, even though it was set to dark, is there any possible way to make this work the way I intended.但是,如果我重新加载网站,它会回到浅色主题,即使它被设置为深色,是否有任何可能的方法可以按照我的意图进行这项工作。

  function toggleTheme() {
    // Obtains an array of all <link>
    // elements.
    // Select your element using indexing.
    var theme = document.getElementsByTagName("link")[0];

    // Change the value of href attribute
    // to change the css sheet.
    if (theme.getAttribute("href") == "light.css") {
      theme.setAttribute("href", "dark.css");
    } else {
      theme.setAttribute("href", "light.css");
    }

You could save theme to localstorage like this:您可以像这样将主题保存到本地存储:

const theme = document.getElementsByTagName('link')[0];
const lightTheme = 'light.css';
const darkTheme = 'dark.css';
const newTheme = theme.getAttribute('href') === lightTheme ? darkTheme : lightTheme;
theme.setAttribute('href', newTheme);
// set new theme as preferred
localStorage.setItem('theme', newTheme);

And after page creation we could check existence of preferred theme:创建页面后,我们可以检查是否存在首选主题:

const theme = document.getElementsByTagName('link')[0];
const themeValue = localStorage.getItem('theme');
if (themeValue) {
    theme.setAttribute('href', themeValue);
}

I think that's a far fetch objective.我认为这是一个遥不可及的目标。 Why don't you make classes for your tags instead.你为什么不为你的标签创建类呢。 For example例如

.dark_body{ background: black;}
.light_body{background:white;}

Then you swap those with JavaScript然后你用 JavaScript 交换它们

BTN.addEventListener('click',()=>{ body.classlist.add('dark_body'); body.classlist.remove('light_body')

And so on.等等。 You can also use toggle method.您也可以使用切换方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM